1.NEW
2.TERMINATED
3.RUNNABLE
4.WAITING
5.TIMED_WAITING
6.BLOCKED
1.NEW
这个状态代表的是start方法执行之前的状态
也就是线程被创建,但还未被执行
java
public static void main1(String[] args) throws InterruptedException {
Thread t = new Thread(()->{
while (true){
System.out.println("hello t");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
System.out.println(t.getState());//在start之前->NEW
t.start();
}
2.TERMINATED
线程方法入口执行完毕
java
public static void main1(String[] args) throws InterruptedException {
Thread t = new Thread(()->{
/*while (true){
System.out.println("hello t");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}*/
});
System.out.println(t.getState());//在start之前->NEW
t.start();
t.join();
System.out.println(t.getState());//t线程执行结束
}
3.RUNNABLE
这个状态细分为两种:分别是就绪队列中的线程和正在执行的线程
java
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(()->{
while (true){
}
});
t.start();
Thread.sleep(10);
System.out.println(t.getState());
}
4.WAITING
死等,join的情况下,比如说main线程等待t线程执行的过程,那么此时的main就是在死等,main的状态就是WAITING
java
public static void main(String[] args) throws InterruptedException {
Thread mainThread = Thread.currentThread();//获取main线程
Thread t = new Thread(()->{
while (true){
System.out.println(mainThread.getState());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
t.start();
t.join();//主线程等待t,此时一直在死等
}
5.TIMED_WAITING
设置了超时时间的等待
比如说join方法添加了等待时间,那么等待的这段时间状态就是TIMED_WAITING
java
public static void main(String[] args) throws InterruptedException {
Thread mainThread = Thread.currentThread();//获取main线程
Thread t = new Thread(()->{
while (true){
System.out.println(mainThread.getState());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
t.start();
t.join(5555);//主线程等待t,此时一直在死等
}
6.BLOCKED
加锁堵塞状态
以上这几种状态作用于调试代码的阶段,用来发现问题