线程转换图

image.png

NEW 状态转换到 RUNNABLE

调用start就可以。

RUNNABLE 与 BLOCKED 的状态转换

只有线程等待 synchronized 的隐式锁

RUNNABLE 与 WAITING 的状态转换

  1. synchronized中调用wait()
  2. Thread.join() 方法

    有一个线程对象 thread A,当调用 A.join() 的时候,执行这条语句的线程会等待 thread A 执行完,而等待中的这个线程,其状态会从 RUNNABLE 转换到 WAITING。当线程 thread A 执行完,原来等待它的线程又会从 WAITING 状态转换到 RUNNABLE。

  3. LockSupport.park()

    RUNNABLE 与 TIMED_WAITING 的状态转换

    TIMED_WAITING 和 WAITING 状态的区别,仅仅是触发条件多了超时参数。

    RUNNABLE 到 TERMINATED 状态

    执行完run方法就结束了
    如果run方法很慢, 可以执行来interrupt终止


思考题

下面代码的本意是当前线程被中断之后,退出while(true),你觉得这段代码是否正确呢?

  1. Thread th = Thread.currentThread();
  2. while(true) {
  3. if(th.isInterrupted()) {
  4. break;
  5. }
  6. // 省略业务代码无数
  7. try {
  8. Thread.sleep(100);
  9. }catch (InterruptedException e){
  10. e.printStackTrace();
  11. }
  12. }

解答

如果sleep的时候 突然执行了interupt 但是此时异常被catch了,那会一直循环下去。

正确的操作是

  1. try {
  2. Thread.sleep(100);
  3. }catch(InterruptedException e){
  4. // 重新设置中断标志位
  5. th.interrupt();
  6. }