多线程核心知识总结(四)——图解线程生命周期

多线程核心知识总结

四.线程生命周期

线程的六种状态

- New

已创建但还未启动的新线程

- Runnable

可运行的,调用start方法之后就会变成Runnable状态,无论是否运行,对应操作系统中的ready和running

- Blocked

当一个线程进入被sychornized修饰的代码块的时候,并且该锁已经被其他线程拿走了,这个时候的状态为Blocked

- Waiting

没有设置time参数的Object.wait()等方法执行后,(具体看图)。

- Timed Waiting

Thread.sleep(time),Object.wait(time),Thread.join(time)等,(具体看图)

- Terminated

执行完成后进入的状态。

New , Runnable , Treminated 的代码演示:

/** * 描述: 展示线程的NEW、RUNNABLE、Terminated状态。即使是正在运行,也是Runnable状态,而不是Running。 */
public class NewRunnableTerminated implements Runnable {
   

    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(1000);
        } catch (InterruptedException e) {
   
            e.printStackTrace();
        }
        //打印出TERMINATED状态
        System.out.println(thread.getState());
    }

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

Blocked ,Waiting,TimedWaiting 的代码演示:

/** * 描述: 展示Blocked, Waiting, TimedWaiting */
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();
        }
    }
}

阻塞的定义

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

常见面试问题

线程有哪几种状态,线程的生命周期是什么?

直接按图理解:

全部评论

相关推荐

09-28 22:01
已编辑
广西科技大学 IT技术支持
合适才能收到offe...:找桌面运维?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务