线程的状态流转
从JAVA源码可以得出有6种状态

NEW、RUNNABLE、BLOCKED、WAITING、TIME_WAITING、TERMINATED
image
通过代码解释说明

  1. 初始化状态是NEW
    public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(() -> {});  System.out.println(thread.getState());
    }
    
    执行结果
    NEW
    
  2. 运行过程的状态是RUNABLE
    public static void main(String[] args) throws InterruptedException {  Thread thread = new Thread(() -> {  while (true) { }  });  thread.start();  Thread.sleep(500);  System.out.println(thread.getState());  
    }
    
    执行结果的确是RUNNABLE
    RUNNABLE
    
  3. 主线程被上锁了,创建的线程无法获取锁,此时的状态是BLOCKED
    public class ThreadStatus {  public static Object obj = new Object();  public static void main(String[] args) throws InterruptedException {  Thread thread = new Thread(() -> {  synchronized (obj) {  while (true){  }  }  });  // 此时住线程持有锁  synchronized (obj){  // 开启新的线程,因为主线程持有锁所以拿不到锁被阻塞  thread.start();  Thread.sleep(500);  System.out.println(thread.getState());  }  }
    }
    
    执行结果是BLOCKED
    BLOCKED
    
  4. 当创建的线程持有锁时状态是WAITING,
    public class ThreadStatus {  public static Object obj = new Object();  public static void main(String[] args) throws InterruptedException {Object obj = new Object();Thread thread = new Thread(() -> {synchronized (obj) {  // 步骤2:新线程获取锁try {obj.wait();   // 步骤3:释放锁,进入WAITING状态} catch (InterruptedException e) {throw new RuntimeException(e);}// 步骤6:被唤醒后重新获取锁,继续执行}});thread.start();           // 步骤1:启动新线程Thread.sleep(500);        // 步骤4:主线程睡眠System.out.println(thread.getState());  // 输出:WAITINGsynchronized (obj) {      // 步骤5:主线程可以获取锁(因为新线程已释放)obj.notify();         // 唤醒新线程}                         // 主线程释放锁Thread.sleep(500);System.out.println(thread.getState());  // 输出:TERMINATED}  
    }
    
    执行结果是
    WAITING
    TERMINATED
    
  5. 当线程处于休眠(sleep())中,状态即为TIMED_WAITING
    public static void main(String[] args) throws InterruptedException {  Thread thread = new Thread(() -> {  try {  Thread.sleep(10000);  } catch (InterruptedException e) {  throw new RuntimeException(e);  }  });  thread.start();  Thread.sleep(500);  System.out.println(thread.getState());  
    }
    
    执行结果是
    TIMED_WAITING
    
  6. 线程执行结束后状态即为TERMINATED
    public static void main(String[] args) throws InterruptedException {  Thread thread = new Thread(() -> {  try {  Thread.sleep(300);  } catch (InterruptedException e) {  throw new RuntimeException(e);  }  });  thread.start();  Thread.sleep(500);  System.out.println(thread.getState());  
    }
    
    执行结果
    TERMINATED