Java线程状态预览

Java线程有五个状态:就绪(刚创建的时候),运行中(RUNNING),限时等待中(TIMED_WAITING),等待中(WAITING),阻塞(BLOCKED)

以下代码模拟线程的各个情况(针对TIMED_WAITING,WAITING和BLOCKED)


public class ThreadStatusDemo {


    public static void main(String[] args) throws Exception{
        Thread waitDemoThread1 = new Thread(new WaitDemo1());
        Thread sleepDemoThread = new Thread(new SleepDemo());
        // waiting状态
        waitDemoThread1.start();
        // timed_waiting状态
        sleepDemoThread.start();
        // blocked状态
        new Thread(new BlockDemo()).start();
        // notify和waiting状态
        new Thread(new WaitDemo2()).start();
        // timed_waiting状态
        sleepDemoThread.join(600000);
    }

    static class WaitDemo1 implements Runnable{

        @Override
        public void run() {
            Thread.currentThread().setName("WaitDemo1");
            synchronized (WaitDemo1.class) {
                try {
                    WaitDemo1.class.wait();
                    System.out.println("WaitDemo1");
                    WaitDemo1.class.wait();
                    System.out.println("WaitDemo1");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class WaitDemo2 implements Runnable{

        @Override
        public void run() {
            Thread.currentThread().setName("WaitDemo2");
            while (true) {
                synchronized (WaitDemo1.class) {
                    WaitDemo1.class.notifyAll();
                }

                synchronized (WaitDemo1.class) {
                    try {
                        WaitDemo1.class.wait();
                        System.out.println("WaitDemo2");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }                }

            }
        }
    }

    static class SleepDemo implements Runnable{

        @Override
        public void run() {
            Thread.currentThread().setName("SleepDemo");

            synchronized (SleepDemo.class) {
                try {
                    while (true) {
                        Thread.currentThread().sleep(5000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class BlockDemo implements Runnable{

        @Override
        public void run() {
            Thread.currentThread().setName("BlockDemo");

            synchronized (SleepDemo.class) {

            }
        }
    }
}

 

查看线程状态可以使用jstack工具,操作步骤:

1、在项目目录下的终端输入jps回车,找到本程序的进程号,本例中是15412

2、在终端中再输入jstack 15412 回车,得到各个线程的运行状态

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值