
线程的生命周期分为 新建,就绪,运行,阻塞,死亡。当线程进入运行状态时,操作系统采用抢占方式为线程分配cpu,此时多个线程之间的资源竞争,就出现了运行状态,阻塞状态,就绪状态的转换。
使用new创建一个线程,此时Java虚拟机就会为其分配内存,并初始化成员变量,此时它只是一个线程对象。
当调用线程的start 方法后,这个线程就处于就绪状态,此时线程并未分配cpu资源,操作系统采用抢占方式,谁先获取cpu,谁就可以运行。
JVM会为其创建方法调用栈和程序计数器。线程的执行由底层平台控制,具有随机性。
处于就绪状态的线程被调度并获取cpu资源时,会进入执行状态(进入run方法)。
早期的单核cpu来说,同时时刻只能执行一条指令,操作系统为了让多个线程能够同时执行,引入了cpu时间片的概念,将cpu分为按照时间分片,操作系统通过快速切换线程执行来实现多线程的运行,这个速度非常快。为了让线程能够恢复到正确的执行位置,每条线程都有一个独立的程序计数器,各线程之间的计数器互不影响,独立存储。
当一个线程开始运行后,它不可能一直占有CPU(除非线程执行体非常短,一个时间片就执行结束了)。所以,线程在执行过程中需要被中断,目的是让其它线程获取cpu资源,线程的调度取决于底层平台策略。
线程运行时,由于某些原因导致其从运行状态变成阻塞状态。
进入阻塞的原因
线程死亡
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
