JAVA 线程状态演示

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:NEW11:03:52.279 [main] DEBUG cn.yds.juc.learning.ThreadStatusDemo - 线程:t2,status:RUNNABLE11:03:52.279 [main] DEBUG cn.yds.juc.learning.ThreadStatusDemo - 线程:t3,status:TERMINATED11:03:52.279 [main] DEBUG cn.yds.juc.learning.ThreadStatusDemo - 线程:t4,status:TIMED_WAITING11:03:52.279 [main] DEBUG cn.yds.juc.learning.ThreadStatusDemo - 线程:t5,status:WAITING11:03:52.280 [main] DEBUG cn.yds.juc.learning.ThreadStatusDemo - 线程:t6,status:BLOCKED

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值