WangJiQing

导航

线程状态演示

线程状态演示

操作系统层面有5中状态

Java中有6种状态

NEW、 RUNNABLE、 BLOCKED、 WAITING、 TIMED_WAITING、 TERMINATED

Thread源码中就有显示,打印出来

演示

@Slf4j
public class TState {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            log.debug("t1 running...");
        }, "t1");

        Thread t2 = new Thread(() -> {
            while (true){

            }
        }, "t2");
        t2.start();

        Thread t3 = new Thread(() -> {
            log.debug("t3 running...");
        }, "t3");
        t3.start();

        Thread t4 = new Thread(() -> {
            synchronized (TState.class){
                try {
                    Thread.sleep(10000000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t4");
        t4.start();

        Thread t5 = new Thread(() -> {
            try {
                t2.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t5");
        t5.start();

        Thread t6 = new Thread(() -> {
            synchronized (TState.class){
                try {
                    Thread.sleep(10000000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t6");
        t6.start();


        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("t1 state: " + t1.getState());
        System.out.println("t2 state: " + t2.getState());
        System.out.println("t3 state: " + t3.getState());
        System.out.println("t4 state: " + t4.getState());
        System.out.println("t5 state: " + t5.getState());
        System.out.println("t6 state: " + t6.getState());
    }
}

posted on 2022-12-20 12:30  如梦幻泡影  阅读(16)  评论(0编辑  收藏  举报