Thread类内的State枚举描述了线程的状态:
public enum State { NEW, // 线程还没有启动 RUNNABLE, // 正在运行 BLOCKED, // 等待监视器锁。在同步代码块外面阻塞住了 WAITING, // 等待Object.notify(),调用Object.wait()后的状态 TIMED_WAITING, //调用Object.wait(1000)或者Thread.sleep(1000)后的状态 TERMINATED; //结束 }
代码示例打印线程状态:
public static void main(String[] args) { final Object obj = new Object(); Thread thread = new Thread(new Runnable() { @Override public void run() { synchronized(obj) { System.out.println(Thread.currentThread().getName()); try { // TIMED_WAITING // Thread.sleep(5000); // WAITING obj.wait(); } catch (InterruptedException e) {} } } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { //线程阻塞在synchronized代码块外,为blocked synchronized(obj) { System.out.println(Thread.currentThread().getName()); try { // TIMED_WAITING obj.wait(1000); } catch (InterruptedException e) {} } } }); thread.start(); thread2.start(); try { Thread.sleep(500); } catch (InterruptedException e) {} System.out.println(thread.getName() + "," + thread.getState()); System.out.println(thread2.getName() + "," + thread2.getState()); }