• 线程的生命周期


    线程的生命周期

    在这里插入图片描述
    线程的生命周期分为 新建,就绪,运行,阻塞,死亡。当线程进入运行状态时,操作系统采用抢占方式为线程分配cpu,此时多个线程之间的资源竞争,就出现了运行状态,阻塞状态,就绪状态的转换。

    新建

    使用new创建一个线程,此时Java虚拟机就会为其分配内存,并初始化成员变量,此时它只是一个线程对象。

    就绪

    当调用线程的start 方法后,这个线程就处于就绪状态,此时线程并未分配cpu资源,操作系统采用抢占方式,谁先获取cpu,谁就可以运行。
    JVM会为其创建方法调用栈和程序计数器。线程的执行由底层平台控制,具有随机性。

    运行

    处于就绪状态的线程被调度并获取cpu资源时,会进入执行状态(进入run方法)。
    早期的单核cpu来说,同时时刻只能执行一条指令,操作系统为了让多个线程能够同时执行,引入了cpu时间片的概念,将cpu分为按照时间分片,操作系统通过快速切换线程执行来实现多线程的运行,这个速度非常快。为了让线程能够恢复到正确的执行位置,每条线程都有一个独立的程序计数器,各线程之间的计数器互不影响,独立存储。
    当一个线程开始运行后,它不可能一直占有CPU(除非线程执行体非常短,一个时间片就执行结束了)。所以,线程在执行过程中需要被中断,目的是让其它线程获取cpu资源,线程的调度取决于底层平台策略。

    阻塞

    线程运行时,由于某些原因导致其从运行状态变成阻塞状态。
    进入阻塞的原因

    • 1 等待网络资源
    • 2 sleep()
    • 3 等待I/O
    • 4 wait
    • 5 其它线程join,当前线程阻塞

    死亡

    线程死亡

    • 1.run方法正常完成
    • 2 未捕获的Exception/Error
    • 3.强行stop(官方已弃用,详见官方解释)

    Java Thread Primitive Deprecation
    Why is Thread.stop deprecated?

    Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged. When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect, or it may be pronounced. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.

    https://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

    线程对象全生命周期状态图

    在这里插入图片描述

  • 相关阅读:
    springboot源码编译报错Unable to start the daemon process
    python+requests+pytest+allure自动化框架
    计算机网络 --- 网络编程
    华为交换机镜像端口配置
    牛顿迭代法求平方根--C++简单实现
    基数排序!
    如何入驻抖音本地生活服务商,附上便捷流程!
    解决OpenCV捕捉USB摄像头时抓帧失败的问题
    品牌化战略:跨境电商市场突破的关键
    RabbitMQ基础
  • 原文地址:https://blog.csdn.net/u011628753/article/details/126891712