package cn.yds.juc.learning;
import lombok.extern.slf4j.Slf4j;
/**
* @author yds
* @Date 2022/9/26 15:54
* @Description ThreadDemo6
* @Version 1.0.0
*/
@Slf4j
public class ThreadStatusDemo {
public static void main(String[] args) throws InterruptedException {
//------>NEW
Thread t1 = new Thread(() -> {
}, "t1");
//------>RUNNABLE
Thread t2 = new Thread(() -> {
//死循环,一直在运行
while (true) {
}
}, "t2");
t2.start();
//------>TERMINATED
Thread t3 = new Thread(() -> {
}, "t3");
t3.start();
//------>TIMED_WAITING
Thread t4 = new Thread(() -> {
synchronized (ThreadStatusDemo.class) {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t4");
t4.start();
//------>WAITING
Thread t5 = new Thread(() -> {
try {
//T2是死循环,一直等待
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t5");
t5.start();
//------>BLOCKED
Thread t6 = new Thread(() -> {
//此处t4先拿到了锁,t6拿不到锁,陷入阻塞
synchronized (ThreadStatusDemo.class) {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t6");
t6.start();
Thread.sleep(1000);
log.debug("线程:{},status:{}", t1.getName(), t1.getState());
log.debug("线程:{},status:{}", t2.getName(), t2.getState());
log.debug("线程:{},status:{}", t3.getName(), t3.getState());
log.debug("线程:{},status:{}", t4.getName(), t4.getState());
log.debug("线程:{},status:{}", t5.getName(), t5.getState());
log.debug("线程:{},status:{}", t6.getName(), t6.getState());
}
}
执行结果:
11:03:52.265 [main] DEBUG cn.yds.juc.learning.ThreadStatusDemo - 线程:t1,status:NEW
11:03:52.279 [main] DEBUG cn.yds.juc.learning.ThreadStatusDemo - 线程:t2,status:RUNNABLE
11:03:52.279 [main] DEBUG cn.yds.juc.learning.ThreadStatusDemo - 线程:t3,status:TERMINATED
11:03:52.279 [main] DEBUG cn.yds.juc.learning.ThreadStatusDemo - 线程:t4,status:TIMED_WAITING
11:03:52.279 [main] DEBUG cn.yds.juc.learning.ThreadStatusDemo - 线程:t5,status:WAITING
11:03:52.280 [main] DEBUG cn.yds.juc.learning.ThreadStatusDemo - 线程:t6,status:BLOCKED