线程转换图
NEW 状态转换到 RUNNABLE
调用start就可以。
RUNNABLE 与 BLOCKED 的状态转换
RUNNABLE 与 WAITING 的状态转换
- synchronized中调用wait()
Thread.join() 方法
有一个线程对象 thread A,当调用 A.join() 的时候,执行这条语句的线程会等待 thread A 执行完,而等待中的这个线程,其状态会从 RUNNABLE 转换到 WAITING。当线程 thread A 执行完,原来等待它的线程又会从 WAITING 状态转换到 RUNNABLE。
-
RUNNABLE 与 TIMED_WAITING 的状态转换
TIMED_WAITING 和 WAITING 状态的区别,仅仅是触发条件多了超时参数。
RUNNABLE 到 TERMINATED 状态
执行完run方法就结束了
如果run方法很慢, 可以执行来interrupt终止
思考题
下面代码的本意是当前线程被中断之后,退出while(true),你觉得这段代码是否正确呢?
Thread th = Thread.currentThread();
while(true) {
if(th.isInterrupted()) {
break;
}
// 省略业务代码无数
try {
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
}
解答
如果sleep的时候 突然执行了interupt 但是此时异常被catch了,那会一直循环下去。
正确的操作是
try {
Thread.sleep(100);
}catch(InterruptedException e){
// 重新设置中断标志位
th.interrupt();
}