Thread几种状态
NEW(未启动状态)
Thread t = new Thread() { @Override public void run() { System.out.println(Thread.currentThread().getName()); } }; System.out.println(t.getState().name());
RUNNABLE(可运行状态)
处于可运行状态的线程正在 Java 虚拟机中执行,但也可能是正在等待来自操作系统资源,例如 CPU。
Thread t = new Thread() { @Override public void run() { System.out.println(Thread.currentThread().getName()); } }; t.start(); System.out.println(t.getState().name());
BLOCKED(阻塞状态)
final Object lock = new Object(); Thread t = new Thread() { @Override public void run() { synchronized (lock) { System.out.println(Thread.currentThread().getName()); } } }; synchronized (lock) { try { t.start(); Thread.sleep(1000); System.out.println(t.getState().name()); } catch (InterruptedException e) { e.printStackTrace(); } }
WAITING(等待状态)
调用以下方法,使线程处于等待状态:
Object.wait()、Thread.join()、LockSupport.park()
TIMED_WAITING(具有指定时间的等待状态)
Thread t = new Thread() { @Override public void run() { try { Thread.sleep(2000); System.out.println(Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } }; t.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(t.getState().name());
TERMINATED(已终止线程的线程状态或线程已完成执行)
Thread t = new Thread() { @Override public void run() { System.out.println(Thread.currentThread().getName()); } }; t.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(t.getState().name());