当前位置:网站首页>线程的生命周期
线程的生命周期
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()方法结束该线程——该方法容易导致死锁,通常不建议使用。
边栏推荐
- When the interviewer asks you to write binarysort in two ways
- 手机炒股开户安不安全?
- Deployment of MySQL database in Linux Environment
- SQL injection file read / write
- APICloud携手三六零天御,助力企业守好App安全“第一关”
- [share OpenGL tutorial]
- 股票 停牌
- The digital human industry is about to break out. What is the market pattern?
- STL -- binder
- 为什么SELECT * 会导致查询效率低?
猜你喜欢

P2394 yyy loves Chemistry I

Apiccloud, together with 360 Tianyu, helps enterprises keep the "first pass" of APP security

数据挖掘建模实战

SQL 优化经历:从 30248秒到 0.001秒的经历

Ingersoll Rand panel maintenance IR Ingersoll Rand microcomputer controller maintenance xe-145m

Test cases for learning the basic content of software testing (II)

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

Common tools for interface testing --postman

学习阿里如何进行数据指标体系的治理

Use of Jasper soft studio report tool and solution of thorny problems
随机推荐
Illustration of MySQL binlog, redo log and undo log
104. maximum depth of binary tree
怎样在手机上开户?现在网上开户安全么?
1180: fractional line delimitation /p1068 [noip2009 popularization group] fractional line delimitation
Discussion on the practice of fire emergency lighting system in the field of building electrical design
Discussion on the improvement and application of the prepayment system in the management of electricity charge and price
Zhejiang energy online monitoring and management system
This article explains in detail the difficult problems and solutions faced by 3D cameras
When the interviewer asks you to write binarysort in two ways
[ybtoj advanced training guide] maximum separation [hash] [Floyd]
DEJA_VU3D - Cesium功能集 之 051-地形开挖完美实现
DEJA_ Vu3d - 051 of cesium function set - perfect realization of terrain excavation
自动转换之-面试题
Fire fighting work and measures in Higher Vocational Colleges
Find the total number of 1 appearing in the integer 1-N and the number of 1 in the binary of the integer
Installation of containerd1.5.5
Screen settings in the source code of OBS Live Room
1182:合影效果
SQL 优化经历:从 30248秒到 0.001秒的经历
手机买同业存单基金开户选哪家证券公司比较好,比较安全呢