当前位置:网站首页>线程的生命周期
线程的生命周期
2022-06-28 09:19:00 【李王家的翠花】
一、概述
线程的生命周期包含5个阶段,包括:新建、就绪、运行、阻塞、死亡。
当线程进入运行状态后,一般的操作系统是采用抢占式的方式来让线程获得CPU。所以CPU需要在多条线程之间切换,于是线程状态也会多次在运行、阻塞、就绪之间切换。
二、新建
新建:使用new方法,new出来线程,此时仅仅由JAVA虚拟机为其分配内存,并初始化成员变量的值。此时仅仅是个对象。
三、就绪
就绪:就是调用的线程的start()方法后,这时候线程处于等待CPU分配资源阶段,谁先抢的CPU资源,谁开始执行;
该线程进入就绪状态,JAVA虚拟机会为其创建方法调用栈和程序计数器。线程的执行是由底层平台控制, 具有一定的随机性。
四、运行
运行:当就绪的线程被调度并获得CPU资源时,便进入运行状态,run方法定义了线程的操作和功能;(当处于就绪状态的线程获得CPU,它就会执行run()方法)
对于一个单核cpu(或者是一个内核)来说,只能同时执行一条指令,而JVM通过快速切换线程执行指令来达到多线程的,真正处理器就能同时处理一条指令,只是这种切换速度很快,我们根本不会感知到。为了线程切换后能恢复到正确的执行位置,每条线程都有一个独立的程序计数器,各条线程之间计数器互不影响,独立存储。
当一个线程开始运行后,它不可能一直持有CPU(除非该线程执行体非常短,瞬间就执行结束了)。所以,线程在执行过程中需要被中断,目的是让其它线程获得执行的CPU的机会。线程的调度细节取决于底层平台所采用的策略。
五、阻塞
阻塞:在运行状态的时候,可能因为某些原因导致运行状态的线程变成了阻塞状态。原因如下:
1.等待I/O流的输入输出
2.等待网络资源,即网速问题
3.调用sleep()方法,需要等sleep时间结束
4.调用wait()方法,需要调用notify()唤醒线程
5.其他线程执行join()方法,当前线程则会阻塞,需要等其他线程执行完。
状态切换图如下:
六、死亡
1、run()/call()方法执行完成,线程正常结束;
2、线程抛出一个未捕获的Exception或Error;
3、直接调用线程的stop()方法结束该线程——该方法容易导致死锁,通常不建议使用。
边栏推荐
- Loggerfactory uses log4j Parameter introduction of properties
- Screen settings in the source code of OBS Live Room
- Check whether the table contains rows SQL Server 2005 - check whether a table contains rows or not SQL Server 2005
- The private attribute of this class can be used directly? New() in use!!!
- 1181:整数奇偶排序
- How to solve the problem of port number occupation
- Resource scheduling and task scheduling of spark
- Android studio interview preparation
- [ybtoj advanced training guidance] class roll call [string hash]
- How to implement two factor authentication MFA based on RADIUS protocol?
猜你喜欢

Discussion on the improvement and application of the prepayment system in the management of electricity charge and price

Common tools for interface testing --postman

104. maximum depth of binary tree

虚拟机14安装win7(图教程)

Discussion on the practice of fire emergency lighting system in the field of building electrical design

Screen settings in the source code of OBS Live Room

Application of current limiting protector in preventing electrical fire in shopping malls

SQL 優化經曆:從 30248秒到 0.001秒的經曆

Rman Backup Report Ora - 19809 Ora - 19804

MATLAB小技巧(20)矩阵分析--主成分回归
随机推荐
RMAN backup message ora-19809 ora-19804
Implementation of single sign on
Batch modify tables and sorting rules for fields in tables
P2394 yyy loves Chemistry I
Calcul des frais d'achat et de vente d'actions
静态代码块永远先执行? 格局小了!!!
01-分布式系统概述
虚拟机14安装win7(图教程)
使用transform:scale之后导致页面鼠标悬浮事件消失
Prototype chain JS
Import and export of a single collection in postman
How to reduce the risk of project communication?
Container adapter - stack: stack queue: queue priority_ Queue: priority queue
Divide and rule classic Hanoi
01 distributed system overview
详解final、finally和finalize
买卖股票费用计算
Automatic conversion - interview questions
Chrome devtools
手机买同业存单基金开户选哪家证券公司比较好,比较安全呢