old《1.1.2 线程状态》:
考研的OS教科书里告诉我们,线程可以有五种状态:开始,就绪,运行,阻塞(等待),结束。而JDK对线程的状态是这样的:
A thread can be in one of the following states:
NEW
A thread that has not yet started is in this state.
RUNNABLE
A thread executing in the Java virtual machine is in this state.
BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED
A thread that has exited is in this state.
其中最明显的NEW对应开始,TERMINATED对应结束。问题是剩下的RUNNABLE,BLOCKED,WAITING,TIMED_WAITING怎么对应。经过代码实验我可以有把握地认为:
RUNNABLE对应教科书里的就绪和运行。理由如下:
在main函数里有如下代码
System.out.println("调用start方法后 thread3:" + thread3.getState().toString());
结果打印 RUNNABLE。此语句在main函数中执行,执行时线程thread3不可能为运行状态,只可能是就绪态。(此处未考虑多CPU的情况)
而BLOCKED,WAITING,TIMED_WAITING则对应于教科书里阻塞的不同情况
old《1.1.3 线程中止》:
线程的 interrupt() 方法并不会中断一个Runnable的线程, 留下文在此供进一步研究:Java多线程之interrupt()的深度研究
old《1.1.4 内存屏障和CPU缓存》:
old《1.1.5 线程通信》:
wait/notify要求在同步代码中使用,免去了死锁的困扰,但是要注意先调用wait,再调用notify,否则wait就永久等待了;
LockSupport.park/unpark没有顺序要求,但是park不会释放锁,在同步代码中使用要防止死锁。
但是"伪唤醒"讲得不明不白的,以后再研究。此文似可为参考
old《1.1.6 线程封闭之ThreadLocal和栈封闭》:
ThreadLocal和方法的局部变量,都可用于实现线程封闭。