线程的状态

线程状态之间的切换

在这里插入图片描述
  线程一共有6种状态。在创建Thread对象,但还未调用start()方法时,线程为NEW状态。调用start()方法后,线程进入RUNNABLE状态。当线程等待synchronized锁时,会进入BLOCKED状态。当线程调用wait()、join()、lock()等方法时,会进入WAITING状态。当线程执行完成之后,并且Thread对象还未被垃圾回收器回收,这时线程状态为TERMINAL。

代码

  通过以下代码可以体现出线程状态之间的切换。

public class TestThread {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Thread thread = new Thread(() -> {
            System.out.println("2: " + Thread.currentThread().getState());
            Sleep.sleep(1);
            System.out.println("do something");
        });
        System.out.println("1: " + thread.getState());
        thread.start();
        thread.join();
        System.out.println("3: " + thread.getState());

        Thread thread2 = new Thread(() -> {
            try {
                LockSupport.park();
                System.out.println("thread2 go on");
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread2.start();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("4: " + thread2.getState());
        LockSupport.unpark(thread2);
        TimeUnit.SECONDS.sleep(1);
        System.out.println("5: " + thread2.getState());

        final Object o = new Object();
        Thread thread3 = new Thread(() -> {
            synchronized (o) {
                System.out.println("thread3 得到锁");
            }
        });
        new Thread(() -> {
            synchronized (o) {
                Sleep.sleep(5);
            }
        }).start();
        Sleep.sleep(1);
        thread3.start();
        Sleep.sleep(1);
        System.out.println("6: " + thread3.getState());
    }
}

class Sleep {
    public static void sleep(int s) {
        try {
            Thread.sleep(s * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

  输出结果:

1: NEW
2: RUNNABLE
do something
3: TERMINATED
4: WAITING
thread2 go on
5: TIMED_WAITING
6: BLOCKED
thread3 得到锁
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值