当前位置:网站首页>Interview must ask | what stages does a thread go through from creation to extinction?
Interview must ask | what stages does a thread go through from creation to extinction?
2022-07-27 04:34:00 【glacier】
Hello everyone , I'm glacier ~~
stay 【 Proficient in high concurrency series 】 Medium 《 High concurrency —— Thread and multithreading 》 In the article , We briefly introduced the life cycle of threads and several important states of threads , And how the thread enters each state is implemented in the form of code .
today , Let's combine Operating system threads and programming language threads Once again, we will explore the life cycle of threads , The life cycle of threads is not as simple as we think !!
Understanding the life cycle of threads essentially understands The state transition mechanism of each node in the life cycle That's all right. . Next , Let's separate Common thread life cycle and Java Thread life cycle of language Explain in detail .
Common thread life cycle
The general thread life cycle can be divided into five states : The initial state 、 Operational state 、 Running state 、 Sleep state and termination state .
We can simply use the figure below to represent these five states .

The initial state
The thread has been created , But it is not allowed to allocate CPU perform . It should be noted that : This state is specific to the programming language , The thread referred to here has been created , Only refers to being created in a programming language , In the operating system , No real threads were created .
Operational state
Threads can be allocated CPU perform . here , The thread in the operating system was successfully created , Can allocate CPU perform .
Running state
When there are idle in the operating system CPU, The operating system will put this idle CPU Assigned to a thread that is in a runnable state , Be assigned to CPU The state of the thread changes to the running state
Sleep state
A running thread invokes a blocked API( for example , Read the file in a blocked way ) Or wait for an event ( for example , Wait for a conditional variable, etc ), The state of the thread will change to sleep state .** The thread is released CPU resources , A dormant thread has no chance to get CPU Right to use .** Once the waiting condition occurs , The thread will transition from sleep to runnable .
Termination status
The thread will enter the termination state after the execution is completed or an exception occurs , A thread in the terminated state does not switch to any other state , It also means that The thread's life cycle is over .
The above is the general thread life cycle , below , Let's look at the comparison Java Thread life cycle in language .
Java Thread life cycle in
Java The thread life cycle in can be divided into six states : Initialization status (NEW)、 Can run / Running state (RUNNABLE)、 Blocked state (BLOCKED)、 No time limit waiting state (WAITING)、 Time limited waiting state (TIMED_WAITING)、 Termination status (TERMINATED).
What we need to understand is : although Java There are many thread states in the language , however , In fact, at the operating system level ,Java Blocking state in thread (BLOCKED)、 No time limit waiting state (WAITING)、 Time limited waiting state (TIMED_WAITING) It's all a state , That is, the sleep state in the general thread life cycle . in other words , as long as Java When the thread in is in these three states , that , This thread has no CPU Right to use .
After understanding these , We can use the following diagram to simply represent Java The life cycle of threads in .

We can also understand the blocking state in this way (BLOCKED)、 No time limit waiting state (WAITING)、 Time limited waiting state (TIMED_WAITING), They are the three causes of thread hibernation !
Next , Let's just see Java How the state in the thread is transformed .
RUNNABLE And BLOCKED State transition
Only one scenario triggers this transformation , It's just thread waiting synchronized Implicit lock .synchronized The method of decoration 、 Only one thread is allowed to execute the code block at the same time , Other threads need to wait .
here , The waiting thread will start from RUNNABLE State transition to BLOCKED state . When the waiting thread gets synchronized When implicitly locked , I'll go from BLOCKED State transition to RUNNABLE state .
here , I need your attention : Thread call blocking API when , At the operating system level , The thread will transition to sleep . But in JVM in ,Java The state of the thread does not change , in other words ,Java The state of the thread is still RUNNABLE state .
JVM Does not care about operating system scheduling related states , stay JVM Point of view , wait for CPU Right to use ( Threads in the operating system are in an executable state ) And wait for IO operation ( Threads in the operating system are dormant ) There is no difference between , Are waiting for a certain resource , therefore , Put them all under RUNNABLE state .
What we usually say Java In call blocking API when , The thread will block , Refers to the state of the operating system thread , Not at all Java State of thread .
RUNNABLE And WAITING State transition
The thread from RUNNABLE The state changes to WAITING There are three scenarios for states in general .
Scene one
get synchronized Thread of implicit lock , Call parameterless Object.wait() Method . At this point, the thread will start from RUNNABLE The state changes to WAITING state .
Scene two
Call parameterless Thread.join() Method . among join() Method is a thread synchronization method . for example , stay threadA Call in thread threadB Thread join() Method , be threadA Thread will wait threadB The thread is finished .
and threadA The thread is waiting threadB During thread execution , Its state will change from RUNNABLE The switch to WAITING. When threadB completion of enforcement ,threadA The state of the thread will change from WAITING The state changes to RUNNABLE state .
Scene three
call LockSupport.park() Method , The current thread will block , The state of the thread will change from RUNNABLE convert to WAITING.
call LockSupport.unpark(Thread thread) Wake up target thread , The state of the target thread will change from WAITING State transition to RUNNABLE.
RUNNABLE And TIMED_WAITING State transition
In general, it can be divided into five scenarios .
Scene one
Call... With timeout parameter Thread.sleep(long millis) Method ;
Scene two
get synchronized Thread of implicit lock , Call... With timeout parameter Object.wait(long timeout) Parameters ;
Scene three
Call... With timeout parameter Thread.join(long millis) Method ;
Scene 4
Call... With timeout parameter LockSupport.parkNanos(Object blocker, long deadline) Method ;
Scene five
Call... With timeout parameter LockSuppor.parkUntil(long deadline) Method .
from NEW To RUNNABLE state
Java Just created Thread Object is NEW state , establish Thread There are two main ways to target , One is inheritance Thread object , rewrite run() Method ; The other is to realize Runnable Interface , rewrite run() Method .
Be careful : This is about creating Thread Object method , Instead of creating a thread , The method of creating a thread includes creating Thread Object method .
Inherit Thread object
public class ChildThread extends Thread{
@Override
public void run(){
// The logic that needs to be executed in the thread
}
}
// Creating thread objects
ChildThread childThread = new ChildThread();
Realization Runnable Interface
public class ChildRunnable implements Runnable{
@Override
public void run(){
// The logic that needs to be executed in the thread
}
}
// Creating thread objects
Thread childThread = new Thread(new ChildRunnable());
be in NEW Threads in state are not scheduled by the operating system , Therefore, it will not execute .Java The thread in the should execute , You need to switch to RUNNABLE state . from NEW State transition to RUNNABLE state , You only need to call the thread object start() The method can .
// Creating thread objects
Thread childThread = new Thread(new ChildRunnable());
// call start() Method to make the thread from NEW State transition to RUNNABLE state
childThread.start();
RUNNABLE To TERMINATED state
The thread is finished run() After the method , Or perform run() Method , Will end , This is the case TERMINATED state . If we need to interrupt run() Method , You can call interrupt() Method .
Okay , That's all for today , I'm glacier , See you next time ~~
At the end
If you want to enter a large factory , I want a promotion and a raise , Or I'm confused about my current job , You can communicate with me by private letter , I hope some of my experiences can help you ~~
Recommended reading :
- 《 True knowledge comes from practice : The strongest seckill system architecture in the whole network , Not every second kill is a second kill !!》
- 《 From zero to hundreds of millions of users , How do I optimize step by step MySQL Database ?( Recommended collection )》
- 《 I further optimized the massive data proofreading system under 100 million traffic e-commerce business with multithreading , Performance is up again 200%!!( The whole process is dry , Recommended collection )》
- 《 I optimized the massive data proofreading system under the 100 million traffic e-commerce business with multithreading , The performance is improved directly 200%!!( The whole process is dry , Recommended collection )》
- 《 I use 10 This diagram summarizes the best learning route of concurrent programming !!( Recommended collection )》
- 《 A faster lock than read-write lock in high concurrency scenario , After reading it, I was completely convinced !!( Recommended collection )》
- 《 Summary of the most complete performance optimization of the whole network !!( Glacier spitting blood finishing , Recommended collection )》
- 《 It's over in three days MyBatis, Everybody, feel free to ask !!( Glacier spitting blood finishing , Recommended collection )》
- 《 I would like to advise those younger students who have just joined the work : If you want to enter a large factory , This knowledge of concurrent programming is something you must master ! Complete learning path !!( Recommended collection )》
- 《 I would like to advise those younger students who have just joined the work : If you want to enter a large factory , These are the core skills you have to master ! Complete learning path !!( Recommended collection )》
- 《 I would like to advise those younger students who have just joined the work : The earlier you know the basics of computers and operating systems, the better ! Ten thousand words is too long !!( Recommended collection )》
- 《 I spent three days developing a national game suitable for all ages , Support for playing music , Now open the complete source code and comments ( Recommended collection )!!》
- 《 I am the author of high concurrency programming with the hardest core in the whole network ,CSDN The most noteworthy blogger , Do you agree ?( Recommended collection )》
- 《 Five years after graduation , From the monthly salary 3000 To a million dollars a year , What core skills have I mastered ?( Recommended collection )》
- 《 I invaded the sister next door Wifi, Find out ...( Whole process actual combat dry goods , Recommended collection )》
- 《 Never try to “ Panda burning incense ”, see , I regret it !》
- 《 Tomb Sweeping Day secretly training “ Panda burning incense ”, As a result, my computer is panda “ Dedicated ”!》
- 《7.3 Ten thousand words liver explosion Java8 New characteristics , I don't believe you can finish it !( Recommended collection )》
- 《 What kind of experience is it to unplug the server during peak business hours ?》
- 《 The most complete network Linux Command summary !!( In the history of the most complete , Recommended collection )》
- 《 use Python I wrote a tool , Perfectly cracked MySQL!!( Recommended collection )》
- 《SimpleDateFormat Why classes are not thread safe ?( Six solutions are attached , Recommended collection )》
- 《MySQL 8 The three indexes added in , Directly to MySQL Take off , You don't even know !!( Recommended collection )》
- 《 Finish off Spring Source code , I open source this distributed caching framework !!( Recommended collection )》
- 《 100 million level traffic high concurrent second kill system Commodities “ Oversold ” 了 , Just because of the JDK There are two huge pits in the synchronization container !!( Record of stepping on the pit , Recommended collection )》
- 《 I would like to advise those younger students who have just joined the work : To learn concurrent programming well , You must pay attention to the pit of these concurrent containers !!( Recommended collection )》
- 《 The company's reporting tools are too difficult to use , I've had one in three days Excel Tools , It's easy to use the direct call of miss operation , Now open source !!( Recommended collection )》
- 《 I would like to advise those younger students who have just joined the work : If you want to enter a large factory , These core concurrent programming skills are what you must master !!( Recommended collection )》
- 《 Interview officer Ali : How to correctly solve the problem of oversold inventory in the high concurrency and high traffic second kill system ?( Recommended collection )》
- 《Redis Summary of five data types and usage scenarios !!( Including complete actual combat cases , Recommended collection )》
Okay , That's all for today , Like it, guys 、 Collection 、 Comment on , Get up with one button three times in a row , I'm glacier , See you next time ~~
边栏推荐
- Plato Farm全新玩法,套利ePLATO稳获超高收益
- Head detached from origin/... Causes push failure
- Brightcove任命Dan Freund为首席营收官
- 【HCIP】重发布、重分布、重分发实验
- 卷积神经网络——24位彩色图像的卷积的详细介绍
- Standard C language 13
- The project parameters are made into configurable items, and the @configurationproperties annotation is used
- 详解左值、右值、左值引用以及右值引用
- C get UUID
- ROS camera calibration sensor_ Msgs/camerainfo message data type and meaning
猜你喜欢

Unity:Resource Merging、Static Batching、Dynamic Batching、GPU Instancing

Anonymous named pipes, understanding and use of interprocess communication in shared memory

一张图看懂KingbaseES V9

【HCIP】重发布、重分布、重分发实验

Post analysis of Data Analyst

Easy to use shell shortcuts

微信小程序轮播图

Rust:axum learning notes (1) Hello World

无有线网络下安装并配置debian

第二轮Okaleido Tiger即将登录Binance NFT,或持续创造销售神绩
随机推荐
【day02】数据类型转换、运算符、方法入门
ROS camera calibration sensor_ Msgs/camerainfo message data type and meaning
Chapter 6: cloud database
IP第十四天笔记
Shell中的文本处理工具、cut [选项参数] filename 说明:默认分隔符是制表符、awk [选项参数] ‘/pattern1/{action1}filename 、awk 的内置变量
grid布局
使用Unity做一个艺术字系统
管理信息系统期末复习
2022-07-26:以下go语言代码输出什么?A:5;B:hello;C:编译错误;D:运行错误。 package main import ( “fmt“ ) type integer in
Unity:Resource Merging、Static Batching、Dynamic Batching、GPU Instancing
[day02] Introduction to data type conversion, operators and methods
项目参数做成可配置项,@ConfigurationProperties注解的使用
Convolution neural network -- convolution of gray image
数据分析师岗位分析
els 方块显示原理
佳明手表怎么设置用户定制显示
QString转换char*
【C语言】递归详解汉诺塔问题
The new Internet era has come. What new opportunities will Web 3.0 bring us
There are two solutions for the feign call header of microservices to be discarded (with source code)