一文详解Java线程的6种状态与生命周期

  public class Demo3 {

  private static Object object ="obj";

  public static void main(String[] args) throws InterruptedException {

  Thread thread0 = new Thread(() -> {

  try {

  // 被阻塞状态(BLOCKED)

  synchronized (object){

  System.out.println("thread0 进入:等待唤醒状态(WAITING)");

  object.wait();

  System.out.println("thread0 被解除完成:等待唤醒状态(WAITING)");

  }

  System.out.println("thread0 "+Thread.currentThread().getState());

  } catch (InterruptedException e) {

  e.printStackTrace();

  }

  });

  // 新创建状态(NEW)

  System.out.println(thread0.getName()+":"+thread0.getState());

  Thread thread1 = new Thread(() -> {

  try {

  System.out.println("thread1 进入:计时等待状态(TIMED_WAITING)");

  Thread.sleep(2);

  System.out.println("thread1 出来:计时等待状态(TIMED_WAITING)");

  } catch (InterruptedException e) {

  e.printStackTrace();

  }

  // 被阻塞状态(BLOCKED)

  synchronized (object){

  System.out.println("thread1 解除:等待唤醒状态(WAITING)");

  object.notify();

  System.out.println("thread1 解除完成:等待唤醒状态(WAITING)");

  }

  System.out.println("thread1 "+Thread.currentThread().getState());

  });

  // 新创建状态(NEW)

  System.out.println(thread1.getName()+":"+thread1.getState());

  printState(thread0);

  printState(thread1);

  // 可运行状态(RUNNABLE)

  thread0.start();

  // 可运行状态(RUNNABLE)

  thread1.start();

  }

  // 使用独立线程来打印线程状态

  private static void printState(Thread thread) {

  new Thread(()->{

  while (true){

  System.out.println(thread.getName()+":"+thread.getState());

  if (thread.getState().equals(Thread.State.TERMINATED)){

  System.out.println(thread.getName()+":"+thread.getState());

  break;

  }

  }

  }).start();

  }

  }