1、RUNNABLE -> BLOCKED
进入Syncronized修饰方法或者代码块,但是未获得monitor锁
2、BLOCKED ->RUNNABLE
获取到monitor锁
3、RUNNABLE ->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状态
public class ThreadState implements Runnable{
@Override
public void run() {
try {
System.out.println("线程开始运行");
long start = System.currentTimeMillis();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
}
long end = System.currentTimeMillis();
System.out.println("打印所有整数耗时: " + (end - start));
Thread.sleep(50);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
System.out.println("线程结束运行");
}
public static void main(String[] args) throws InterruptedException {
ThreadState threadStateA = new ThreadState();
Thread thread = new Thread(threadStateA);
//新建
System.out.println("新建:" + thread.getState());
thread.start();
System.out.println("start:" + thread.getState());
Thread.sleep(1);
//运行中
System.out.println("运行中:" + thread.getState());
Thread.sleep(20);
System.out.println("sleep:" + thread.getState());
Thread.sleep(200);
//运行完毕
System.out.println("运行完毕:" + thread.getState());
}
}
输出
新建:NEW
start:RUNNABLE
线程开始运行
运行中:RUNNABLE
打印所有整数耗时: 3
sleep:TIMED_WAITING
线程结束运行
运行完毕:TERMINATED
2、BLOCK 和 WAITING
public class ThreadStateTwo implements Runnable{
@Override
public void run() {
synchronized (this){
try {
Thread.sleep(100);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
ThreadStateTwo threadStateTwo = new ThreadStateTwo();
Thread threadA = new Thread(threadStateTwo);
Thread threadB = new Thread(threadStateTwo);
threadA.start();
Thread.sleep(10);
threadB.start();
Thread.sleep(10);
System.out.println("synchronized:" + threadB.getState());
Thread.sleep(100);
System.out.println("wait:" + threadB.getState());
}
}
输出
synchronized:BLOCKED
wait:TIMED_WAITING