传统意义的线程包含6种状态(从操作系统图层面),分别为:新建状态(new),就绪状态(ready),运行状态(run),等待状态(waiting),结束状态(terminate)。如下图所示:
Java中给线程准备的6种状态:
NEW:Thread对象被创建出来了,但是还没有执行start方法。
RUNNABLE:Thread对象调用了start方法,就为RUNNABLE状态(CPU调度/没有调度)
BLOCKED、WAITING、TIME_WAITING:都可以理解为是阻塞、等待状态,因为处在这三种状态下,CPU不会调度当前线程
BLOCKED:synchronized没有拿到同步锁,被阻塞的情况
WAITING:调用wait方法就会处于WAITING状态,需要被手动唤醒
TIME_WAITING:调用sleep方法或者join方法,会被自动唤醒,无需手动唤醒
TERMINATED:run方法执行完毕,线程生命周期到头了。
在Java代码种验证各个状态:
NEW状态:
package ThreadState;
public class NewState {
public static void main(String[] args) {
Thread t1 = new Thread(()->{
});
System.out.println(t1.getState());
}
}
RUNNABLE状态:
public class RunnableState {
public static void main(String[] args) throws InterruptedException {
Thread t1 =new Thread(()->{
while (true){}
});
t1.start();
Thread.sleep(500);
System.out.println(t1.getState());
}
}
BLOCKED状态:
public class BlockState {
public static void main(String[] args) throws InterruptedException {
Object o1=new Thread();
Thread t1 =new Thread(()->{
synchronized (o1){
}
});
synchronized (o1){
t1.start();
Thread.sleep(500);
System.out.println(t1.getState());
}
}
}
WAITING状态:
public class WaitState {
public static void main(String[] args) throws InterruptedException {
Object o1=new Object();
Thread t1 =new Thread(()->{
synchronized (o1){
try {
o1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
Thread.sleep(500);
System.out.println(t1.getState());
}
}
TIMED_WAITING状态:
package ThreadState;
public class TimeWaitState {
public static void main(String[] args) throws InterruptedException {
Thread t1=new Thread(()->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
Thread.sleep(500);
System.out.println(t1.getState());
}
}
TERMINATED状态:
package ThreadState;
public class TerminateState {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
Thread.sleep(1000);
System.out.println(t1.getState());
}
}