1、RUNNABLE -> BLOCKED
进入Syncronized修饰方法或者代码块,但是未获得monitor锁
2、BLOCKED ->RUNNABLE
获取到monitor锁
3RUNNABLE ->WAITING
Object.wait()
Thread.join()
LockSupport.unpark()
4、**WAITING ->RUNNABLE
Object.notify()
Object.notifyAll()
LockSupport.unpark()
5、**RUNNABLE ->TIMED_WAITING
Thread.sleep(time)
Object.wait(time)
Thread.join(time)
LockSupport.parkNanos(time)
LockSupport.parkUnit(time)
6、**TIMED_WAITING ->RUNNABLE
等待时间到
Object.notify()
Object.notifyAll()
LockSupport.unpark()
7、WAITING ->BLOCKED
从object.wait()状态刚被唤醒时,通常无法立刻抢到minotor锁,就会从WAITING状态先进入BLOCK状态再转到 RUNNABLE状态。
8、TIEMED_WAITING ->BLOCKED
与7同理
9、异常情况
如果发生异常,可以直接跳到终止Terminated状态,不必遵循路径**

1、NEW ,RUNNABLE,TIMEWAITING,TERMINATED

注:
RUNNABLE对应两种状态即调用start等待cpu调度的ready状态,和已经开始运行的running状态

  1. public class ThreadState implements Runnable{
  2. @Override
  3. public void run() {
  4. try {
  5. System.out.println("线程开始运行");
  6. long start = System.currentTimeMillis();
  7. for (int i = 0; i < Integer.MAX_VALUE; i++) {
  8. }
  9. long end = System.currentTimeMillis();
  10. System.out.println("打印所有整数耗时: " + (end - start));
  11. Thread.sleep(50);
  12. } catch (InterruptedException interruptedException) {
  13. interruptedException.printStackTrace();
  14. }
  15. System.out.println("线程结束运行");
  16. }
  17. public static void main(String[] args) throws InterruptedException {
  18. ThreadState threadStateA = new ThreadState();
  19. Thread thread = new Thread(threadStateA);
  20. //新建
  21. System.out.println("新建:" + thread.getState());
  22. thread.start();
  23. System.out.println("start:" + thread.getState());
  24. Thread.sleep(1);
  25. //运行中
  26. System.out.println("运行中:" + thread.getState());
  27. Thread.sleep(20);
  28. System.out.println("sleep:" + thread.getState());
  29. Thread.sleep(200);
  30. //运行完毕
  31. System.out.println("运行完毕:" + thread.getState());
  32. }
  33. }

输出

  1. 新建:NEW
  2. startRUNNABLE
  3. 线程开始运行
  4. 运行中:RUNNABLE
  5. 打印所有整数耗时: 3
  6. sleepTIMED_WAITING
  7. 线程结束运行
  8. 运行完毕:TERMINATED

2、BLOCK 和 WAITING

  1. public class ThreadStateTwo implements Runnable{
  2. @Override
  3. public void run() {
  4. synchronized (this){
  5. try {
  6. Thread.sleep(100);
  7. wait();
  8. } catch (InterruptedException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. }
  13. public static void main(String[] args) throws InterruptedException {
  14. ThreadStateTwo threadStateTwo = new ThreadStateTwo();
  15. Thread threadA = new Thread(threadStateTwo);
  16. Thread threadB = new Thread(threadStateTwo);
  17. threadA.start();
  18. Thread.sleep(10);
  19. threadB.start();
  20. Thread.sleep(10);
  21. System.out.println("synchronized:" + threadB.getState());
  22. Thread.sleep(100);
  23. System.out.println("wait:" + threadB.getState());
  24. }
  25. }

输出

  1. synchronized:BLOCKED
  2. wait:TIMED_WAITING