深入浅出Java并发多线程(7)- 线程的一生(6个状态)

1 每个状态的含义

在这里插入图片描述

  • New,线程已经创建,但是还没有启动
  • Runnable,可运行的,不是运行中的,一旦调用 start 方法,线程就会进入 Runnable状态。也就是说从NewRunnable,不会从 NewWaiting。java 的Runnable 对应操作系统ReadyRunning
  • Blocked,当一个线程进入到被 synchronized修饰的代码块的时候,并且该锁已经被其他线程拿走了,此时线程状态就是 Blocked
  • Waiting,(1)没有设置timeout的Object.wait()方法,
    在这里插入图片描述

/**
 * @Description 线程的New,Runnable,Terminated状态
 *              即使是正在运行,也是Runnable状态,而不是Running
 * @Author tzb
 * @Date 2020/12/9 22:46
 * @Version 1.0
 **/
public class NewRunnableTerminated implements Runnable{

    public static void main(String[] args) {
        final Thread thread = new Thread(new NewRunnableTerminated());
        // NEW状态
        System.out.println(thread.getState());

        thread.start();
        System.out.println(thread.getState());
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // Runnable
        System.out.println(thread.getState());

    }

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

/**
 * @Description 展示Blocked, Waiting, TimedWaiting状态
 * @Author tzb
 * @Date 2020/12/10 21:49
 * @Version 1.0
 **/
public class BlockedWaitingTimedWaiting implements Runnable {

    public static void main(String[] args) {
        final BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
        final Thread thread1 = new Thread(runnable);
        thread1.start();

        final Thread thread2 = new Thread(runnable);
        thread2.start();

        // 线程1:TIMED_WAITING,因为正在执行睡眠
        System.out.println("线程1:" + thread1.getState());

        // 线程2:BLOCKED,因为thread2想拿到 syn方法的锁,但是拿不到,thread1持有
        System.out.println("线程2:" + thread2.getState());

        try {
            Thread.sleep(1300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        // 线程1:WAITING,因为执行了wait(),但是没有被唤醒
        System.out.println("线程1:" + thread1.getState());

    }


    @Override
    public void run() {
        syn();
    }

    private synchronized void syn() {
        try {
            Thread.sleep(1000);

            wait();

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

2 阻塞状态

  • 一般,把 Blocked,Waiting,Timedwaiting(计时等待) 都称为阻塞状态;
  • 不仅仅是 Blocked

3 常见面试问题

  1. 线程有哪几种状态?生命周期是什么?
    见上图
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值