第六章、核心4:图解线程生命周期

1、有哪6种状态?

2、每个状态是什么含义?

  • New:新建还未执行(start())
  • Runnable(可运行的):调用了start方法后,就会变为Runnable状态
  • Blocked:进入synchronized修饰的区域,同时锁被其他线程拿走
  • Waiting:只能手工唤醒
  • Timed Waiting:计时等待。等到固定time时间后,就可以被唤醒;或者通过手工唤醒2种方式都可以
  • Terminated:程序正常执行完毕;或者出现没有被捕获的异常,中止了run方法

3、状态间的转化图示

第六章、核心4:图解线程生命周期_第1张图片

3.1 代码示例

  • NEW、RUNNABLE、Terminated
/**
 * NewRunnableTerminated
 *
 * @author venlenter
 * @Description: 展示线程的NEW、RUNNABLE、Terminated状态。即使是正在运行,也是Runnable状态,而不是Running
 * @since unknown, 2020-04-07
 */
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());
        //打印出NEW的状态
        System.out.println(thread.getState());
        thread.start();
        System.out.println(thread.getState());
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //打印出RUNNABLE的状态,即使是正在运行,也是RUNNABLE,而不是RUNNING
        System.out.println(thread.getState());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //打印出TERMINATED状态
        System.out.println(thread.getState());
    }
}
//输出结果
NEW
RUNNABLE
0
1
2
...
501
RUNNABLE
502
503
...
999
TERMINATED
  • Blocked,Waiting,TimedWaiting
/**
 * BlockedWaitingTimedWaiting
 *
 * @author venlenter
 * @Description: 展示Blocked,Waiting,TimedWaiting
 * @since unknown, 2020-04-08
 */
public class BlockedWaitingTimedWaiting implements Runnable {
    public static void main(String[] args) {
        BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
        Thread thread1 = new Thread(runnable);
        thread1.start();
        Thread thread2 = new Thread(runnable);
        thread2.start();
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //打印出Timed_Waiting状态,因为正在执行Thread.sleep(1000);
        System.out.println(thread1.getState());
        //打印出BLOCKED状态,因为thread2想拿得到sync()的锁却拿不到
        System.out.println(thread2.getState());
        try {
            Thread.sleep(1300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //打印出WAITING状态,因为执行了wait()
        System.out.println(thread1.getState());
    }

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

    private synchronized void syn() {
        try {
            Thread.sleep(1000);
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
//输出结果
TIMED_WAITING
BLOCKED
WAITING

4、阻塞状态是什么?

  • 一般习惯而言,把Blocked(被阻塞)、Waiting(等待)、Timed_waiting(计时等待)都称为阻塞状态
  • 不仅仅是Blocked

5、常见面试问题

  • 线程有哪几种状态?生命周期是什么? 第六章、核心4:图解线程生命周期_第2张图片

你可能感兴趣的:(深入浅出Java并发多线程)