多线程学习(一)—— 线程的生命周期

线程的 6 种状态

  • New:已创建,未启动,已做好准备工作
  • Runnable:可运行的,调用start()方法后
  • Blocked:阻塞,进入synchronized相关方法或代码块,未持有锁
  • Waiting:进入等待状态(wait(), join(), park()),同样唤醒方法(notify(), notifyAll(), unpark(), 其中join方法要等到join执行的线程执行完毕才被唤醒)
  • Timed Waiting:计时等待,需要指定时间参数,可提前被唤醒,或者等待超时后
  • Terminated:终止,run方法执行完毕;出现未捕获的异常意外终止

Blocked、Waiting、TimedWaiting都成为阻塞状态
在这里插入图片描述

代码演示

New / Runnable / Terminated 状态

public class NewRunnableTerminated implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new NewRunnableTerminated());
        // 创建线程,未启动
        System.out.println(thread.getState());
        thread.start();
        // 启动线程,可能还未运行
        System.out.println(thread.getState());
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 已运行
        System.out.println(thread.getState());

        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 运行完毕
        System.out.println(thread.getState());
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Blocked / Waiting / TimedWaiting 状态

public class BlockedWaitingTimedWaiting implements Runnable{
    @Override
    public void run() {
        syn();
    }
    private synchronized void syn() {
        try {
            Thread.sleep(1000);
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
        Thread thread01 = new Thread(runnable);
        thread01.start();
        Thread thread02 = new Thread(runnable);
        thread02.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 线程1正在执行 Thread.sleep(1000),状态为 TIMED_WAITING
        System.out.println(thread01.getName() + ": " + thread01.getState());
        // 线程2未拿到锁,处于 BLOCKED 状态
        System.out.println(thread02.getName() + ": " + thread02.getState());
        try {
            Thread.sleep(1400);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // wait() 使得进入 WAITING 状态
        System.out.println(thread01.getName() + ": " + thread01.getState());
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值