Java线程的六种状态

Java线程的六种状态

image.png

  1. NEW
  2. RUNNABLE
  3. BLOCKED
  4. WAITING
  5. TIMED_WAITING
  6. TERMINATED
public class ThreadState {

    public static void main(String[] args) throws Exception {
        testTerminated();
    }

    public static void testNewAndRunnable() {
        Thread thread = new Thread(() -> {});
        System.out.println(thread.getState()); //NEW
        thread.start();
        System.out.println(thread.getState()); //RUNNABLE
    }

    public static void testBlocked() throws InterruptedException {
        Object obj = new Object();
        Thread thread = new Thread(() -> {
            //thread未获取到obj锁资源,所以状态为阻塞
            synchronized (obj) {
                System.out.println("execute");
            }
        });
        //主线程获取到了锁资源
        synchronized (obj) {
            thread.start();
            Thread.sleep(1);
            System.out.println(thread.getState()); //BLOCKED
        }
    }

    public static void testWaiting() throws Exception {
        Object obj = new Object();
        Thread thread = new Thread(() -> {
            synchronized (obj) {
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.start();
        Thread.sleep(500);
        System.out.println(thread.getState()); //WAITING
    }

    public static void testTimedWaiting() throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        //thread线程启动后,主线程休眠了0.5秒再获取thread的状态,此时thread线程还在休眠中
        thread.start();
        Thread.sleep(500);
        System.out.println(thread.getState()); //TIMED_WAITING
    }

    public static void testTerminated() throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        //thread线程启动后,主线程休眠了1秒再获取thread的状态,此时thread线程已经执行完毕
        thread.start();
        Thread.sleep(1000);
        System.out.println(thread.getState()); //TERMINATED
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值