Java 中 Thread 的状态
Java juc 面试 About 1,690 words示意图
NEW 初始化状态
new
一个Thread(Runnable)
或Thread
子类等(不调用start()
方法),线程就进入NEW
状态。
Thread thread1 = new Thread(() -> {
});
// thread1 state#NEW
System.out.println("thread1 state#" + thread1.getState().name());
RUNNABLE 可运行状态
可运行状态又分为就绪状态和运行中状态。
Thread thread2 = new Thread(() -> { });
thread2.start();
// thread2 state#RUNNABLE
System.out.println("thread2 state#" + thread2.getState().name());
READY 就绪状态
- 调用
start()
方法 - 调用
yield()
方法 sleep()
方法结束后- 其他线程
join()
后 - 当前线程时间片用完了
RUNNING 运行中状态
正在运行任务的线程。
TERMINATED 终止状态
任务执行完成后状态为TERMINATED
。
Thread thread3 = new Thread(() -> { });
thread3.start();
TimeUnit.MILLISECONDS.sleep(10);
// thread3 state#TERMINATED
System.out.println("thread3 state#" + thread3.getState().name());
TIMED_WAITING 等待超时状态
以下5
个方法使RUNNABLE
状态的线程变为TIMED_WAITING
状态。
- Thread.sleep(long)
- Object.wait(long)
- Thread.join(long)
- LockSupport.parkNanos()
- LockSupport.parkUntil()
Thread thread4 = new Thread(() -> {
LockSupport.parkNanos(1000*1000*1000);
});
thread4.start();
TimeUnit.MILLISECONDS.sleep(10);
// thread4 state#TIMED_WAITING
System.out.println("thread4 state#" + thread4.getState().name());
WAITING 等待状态
以下5
个方法使RUNNABLE
状态的线程变为TIMED_WAITING
状态。
- Object.wait()
- Thread.join()
- LockSupport.park()
Thread thread5 = new Thread(LockSupport::park);
thread5.start();
TimeUnit.MILLISECONDS.sleep(10);
// thread5 state#WAITING
System.out.println("thread5 state#" + thread5.getState().name());
BLOCKED 阻塞状态
等待锁释放
Thread thread6 = new Thread(() -> {
synchronized (Object.class) {
}
});
thread6.start();
synchronized (Object.class) {
TimeUnit.MILLISECONDS.sleep(10);
// thread6 state#BLOCKED
System.out.println("thread6 state#" + thread6.getState().name());
}
Views: 3,143 · Posted: 2021-04-11
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...