线程状态之间的切换
线程一共有6种状态。在创建Thread对象,但还未调用start()方法时,线程为NEW状态。调用start()方法后,线程进入RUNNABLE状态。当线程等待synchronized锁时,会进入BLOCKED状态。当线程调用wait()、join()、lock()等方法时,会进入WAITING状态。当线程执行完成之后,并且Thread对象还未被垃圾回收器回收,这时线程状态为TERMINAL。
代码
通过以下代码可以体现出线程状态之间的切换。
public class TestThread {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Thread thread = new Thread(() -> {
System.out.println("2: " + Thread.currentThread().getState());
Sleep.sleep(1);
System.out.println("do something");
});
System.out.println("1: " + thread.getState());
thread.start();
thread.join();
System.out.println("3: " + thread.getState());
Thread thread2 = new Thread(() -> {
try {
LockSupport.park();
System.out.println("thread2 go on");
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread2.start();
TimeUnit.SECONDS.sleep(1);
System.out.println("4: " + thread2.getState());
LockSupport.unpark(thread2);
TimeUnit.SECONDS.sleep(1);
System.out.println("5: " + thread2.getState());
final Object o = new Object();
Thread thread3 = new Thread(() -> {
synchronized (o) {
System.out.println("thread3 得到锁");
}
});
new Thread(() -> {
synchronized (o) {
Sleep.sleep(5);
}
}).start();
Sleep.sleep(1);
thread3.start();
Sleep.sleep(1);
System.out.println("6: " + thread3.getState());
}
}
class Sleep {
public static void sleep(int s) {
try {
Thread.sleep(s * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出结果:
1: NEW
2: RUNNABLE
do something
3: TERMINATED
4: WAITING
thread2 go on
5: TIMED_WAITING
6: BLOCKED
thread3 得到锁