当前位置:网站首页>About the concept of thread (1)
About the concept of thread (1)
2022-07-24 12:51:00 【Yaya pear】
Article reference :
Java Thread details , Write very well
One Recognize threads
What is thread
A thread is an entity of a process , yes CPU Basic unit of dispatch and dispatch , It is a smaller basic unit that can run independently than a process . Threads themselves do not own system resources , Have only a few essential resources in operation ( For example, program counter , A set of registers and stacks ), But it can share all the resources owned by the process with other threads belonging to the same process . One thread can create and undo another thread , Multiple threads in the same process can execute concurrently . The thread is ready , There are three states of blocking and running .
Here is a thing called process . Although it's simple, we all know it , But write it down ! A process refers to a running application , Each process has its own independent address space , That is, memory space . For example, the user clicks on the desktop IE browser , It starts a process , The operating system will allocate a separate address space for the process . When the user clicks on the left again IE browser , It starts another process , The operating system will allocate a new independent address space for the new process .
2 Hardware thread and software thread
http://www.uedsc.com/reading-thread.html
Multi core microprocessors have more than one physical core , The physical kernel is a truly independent processing unit , Multiple physical cores enable multiple instructions to run in parallel . In order to give full play to the effectiveness of the physical core , It is necessary to run multiple processes , Or running multiple threads in a process , Create multithreaded code .
However, each physical kernel may provide multiple hardware threads , That is, logical kernel or logical processor . Microprocessors using hyper threading technology provide multi architecture state on each physical core , For example, many have 4 Microprocessors with physical cores and hyper threading technology provide two architectural states on each physical core , So we get 8 Hardware threads . This technique is called symmetric multithreading , It optimizes and enhances parallel execution at the instruction level of the microprocessor through additional architectural state , Symmetric threading technology is not limited to two hardware threads per physical kernel , There are plenty of them 4 individual . So it can be seen that , A hardware thread does not represent a physical kernel . In some cases , Symmetric threading technology can improve the performance of multithreaded code .
On the operating system , such as windows in , Every running program is a process . At least one thread is running in each process , This kind of thread is called software thread , Used to distinguish the previously mentioned hardware threads . A process has at least one thread , And there must be a main thread . The scheduler of the operating system fairly shares available processing resources among all threads to be run .Windows The scheduler of will allocate processing time to each software thread . When windows When the scheduler runs on a multi-core microprocessor , The scheduler must allocate time from the hardware threads supported by the physical kernel to each software thread that needs to run instructions . For example , Imagine every hardware thread as a swimlane , The software thread is the swimmer above . And a scheduler is also responsible for when the swimmer will swim in the lane , When to stop in the swimming lane .
Windows Identify each hardware thread as a schedulable logical processor . Each logical processor can run the code of the software thread . Processes running multiple software threads can give full play to the advantages of hardware threads and physical cores , Parallel running instructions .
Each thread shares a private and unique memory space with its parent process . But every software thread has its own stack , register and Private local storage area .
windows The scheduler can decide to assign one software thread to another hardware thread , In this way, the load of each hardware thread is balanced . Because there are usually other software threads waiting for processing time , therefore , Load balancing mechanism can reasonably combine effective resources , Let other software also have the opportunity to execute their own instructions .
Brief description of load balancing : He refers to distributing the tasks of software threads to multiple hardware threads to operate , Through load balancing , Workload can be fairly distributed among hardware threads . However, whether load balancing can be achieved perfectly depends on the parallelism of the application , The workload , Number of software threads , Available hardware threads and load balancing strategies .
The ultimate goal of multithreading is to maximize the use of CPU resources , Remember to make full use of CPU resources , And reach the users , I feel good soon . Instead of improving cpu Operating efficiency . Operational efficiency , Unless you change one CPU Well ,, It is estimated that there is not much discount . So we can make good use of multithreading , Determines the program you develop , On the same machine , Is it better and faster to use than what others have developed .
Scheduling of software threads
The above content involves the word thread scheduling , Strictly speaking, it is for the scheduling of software threads . Let's take a look at what software scheduling is .
It can be seen from the above explanation of hardware thread and software thread , You can even treat the hardware thread as a real object ( In spite of the irrationality , But it's easy to understand ),cpu A quarter or an eighth of the kernel , You can even disassemble the motherboard or something. Anyway, you can see it , As for the principle inside, ignore . They are due to the scheduling of the operating system scheduler , Maybe sometimes some parts will stop working to save electricity . You can think of hardware threads as logical processors . The software thread we call depends on these logic processors to run . And software thread can be regarded as a basic unit , It can also be regarded as a task , Anyway, I feel very confused about the explanation of the unit here , How can it be a unit to make cpu To run these logic, at least you have to be a thread , At least you have one thread before I can run , otherwise , You can even make a whole ( Is not a unit ) Not even , Unable to run ! Um. , A hardware thread can run ( Processing logic in threads ) More than one software thread , And the scheduler of hardware thread, the Butler, can also control which hardware thread the software thread should execute on .
In that case , Generally, there will be 1 To n Unequal threads . Suppose a process starts 32 Threads , Then the actual hardware thread is 8 individual ,, How to adjust , On average, each hardware thread runs four , What's going on ? State guaranteed distribution hahaha , This leads to thread scheduling
In a process 32 Threads , In fact, many processes in real life really have so many threads . So why should there be multithreading ? Imagine a scene , Suppose your mobile phone , And the slag processor has only one hardware thread ,, However, you have a need for development work , Let you watch TV and download ,, You can't do it with just one software thread , If a software thread , What will happen ? Or download the file first , Or watch TV first ? It doesn't meet the demand, so ! So if you only use one thread, you'll only be confused . Then I'll start two threads , Watch a video with , One for downloading files , Then these two threads have to run on the same hardware thread , Just imagine , If you don't schedule these two threads ,, Then you'd better run it first a The logic of the thread runs again b The logic ? This is not the same as you do this first and then do that . This obviously won't work ! So there must be a set of things to control these two threads , How to get there ,, Can simulate me walking at the same time a Logic and b The illusion of logic . At least the effect is that both are going on , Fortunately, the processor runs faster , I'll run it later a, Then run again later b, Run alternately ,, It looks like two threads are running at the same time , Anyway, the processor runs fast , Capricious , It's frequent , The human eye can't perceive the deception hahaha , This strategy can be said to be a easy Thread scheduling for .
The model of thread scheduling ( What kind of scheduling method ):
- Time sharing scheduling model
- Preemptive scheduling model
Time sharing scheduling : It means that all threads take turns to get cpu Right to use , And equally allocate each thread cpu Time slice .
preemptive scheduling : It refers to the limited occupation of threads with high priority in the runnable pool cpu, If the priority of the runnable thread pool is the same , Just randomly select a thread , To occupy cpu. The running thread will run all the time , Until it had to give up cpu. ( What is having to give up ?)
“ Have to give up ” The explanation of
A thread will be abandoned for the following reasons cpu:
- java The virtual machine makes the current thread abandon temporarily cpu, Go to ready state , Give other threads a chance to run . ( forehead ,, It's like a scheduler )
- The current thread is blocked for some reason ( There are many kinds of reasons here for temporary neglect )
- The thread has finished running .
It should be noted that : Thread scheduling is not cross platform , It doesn't just depend on java virtual machine , It also depends on the operating system . In some operating systems , As long as the running thread does not encounter blocking , Will not give up cpu, In some operating systems , Even if the thread does not encounter blocking , It will also run for a period of time and give up cpu, Give other threads a chance .
stay java Inside , His thread scheduling adopts preemptive scheduling model , Not time-sharing , After starting multiple threads at the same time , There is no guarantee that each thread will take turns and get equal cpu Time slice . If you want to explicitly let one thread give another thread a chance to run , You can take one of the following methods :( It doesn't matter if you don't understand these now , Next I'll talk about )
- Let the running thread call Thread.sleep();
- Let the running thread call Thread.yield() Method
- Having a running thread call another thread's join() Method
Two Understanding threads
The difference between thread objects and threads
First, we should make clear the problem , Like the difference between program and process , To understand threads , Multithreading , The first thing to be clear about is , The difference between thread objects and threads .
Thread objects are objects that can generate threads , such as java Upper thread,Runnable object . And threads , It refers to a sequence of instruction points being executed . stay java Platform refers to a thread object from start() Start , function run() The relatively independent logical process in the method body .
So start with the simplest , our main Method
public static void main(String[] args) {
for(int i = 0; i < 100; i ++) {
System.out.println(i + "");
}
}
If the... Is successfully compiled java file , Then type in the command to run the file . Then it will happen :
- JVM The process is started , In the same JVM In progress , There is and only one process , It's him .
- And then here JVM Environment , All programs run on threads .JVM A main thread will be generated first , It runs the entry point of the specified program . In the code above , This entrance is main Method . When main After the method is over , Main thread running completed ,JVM It will exit with it .
- What we see is a main thread running main Method , Such a process with only one thread executing the program is called single thread . This is a JVM The single threaded environment provided to us , in fact ,JVM At the bottom, there are at least background threads such as garbage collection and other non java Threads , But these threads are inaccessible to us , So we think of it as a single thread . And the main thread is JVM I drove it myself , It is not generated by thread objects here . In this thread , It runs the main The logic of the method
The life cycle of a thread ( This is the foundation. )
Threads are periodic . When the thread is created and started , It does not enter the execution state as soon as it is started , It's not always in execution . Threads go through a life cycle , establish , be ready , function , Blocking , Death .5 States . Especially after the thread executes , It is impossible to occupy cpu Running alone , After all, there is thread scheduling , Even if the thread wants to do this , The scheduling mechanism does not allow , There are usually multiple threads in the process , therefore cpu Need to switch between multiple threads , So the state of the thread will be running many times –> Blocking –> be ready –> function –> Blocking –> be ready –> function Switch back and forth . The following is a brief description of these States .
- New state : When the program USES new Keyword created a thread after , He immediately entered the new state , At this time, only by JVM Allocate memory for it , And initialize the value of its member variable .
- Ready state : When a thread object calls start After method , The thread is in a ready state .java Virtual opportunity creates call stacks and program counters for it , Wait for the schedule to run . ( Threads hold three things , The call stack , Counter , And registers )
- Running state : If the thread in the ready state gets cpu, Start execution run Method , Then the thread is running .
- Blocked state : When a running thread loses its resources , It's going to be blocked . There are several reasons why threads are blocked
1. The thread called itself sleep(), Enter the sleep operation
2. The thread executes a piece of synchronization code , However, the relevant synchronization lock cannot be obtained , It can only enter the blocking state , Wait until you get the synchronization lock , To resume execution ( This I don't quite understand )
3. The thread executed the... Of an object wait() Method , Directly into the blocking state , Waiting for other threads notify() perhaps notifyAll()
4. The thread executes some io operation , It enters a blocking state because it waits for related resources . For example, monitoring system.in This input , But there is no keyboard input , It enters a blocked state . - Death state : When run The method exits normally or an uncaught exception terminates the leap method, causing the thread to die suddenly . You enter the state of death
New and ready status :
When the program USES new Keyword after creating a thread , The thread is in the new state , At this time, he and others java object , Only by java The virtual machine allocates memory for it , And initialize the value of its member variable . At this time, the thread object does not show any dynamic characteristics of threads , Of course, the program will not execute threads .
When a thread object calls start() After method , The thread is in a ready state ,java The virtual machine creates method call stacks and program counters for it , The thread in this state is not running , It just means that the thread can run , As for when to start running , Then we have to see JVM Scheduling of thread scheduler . Just let it be ..
( Be careful : Start the thread with start() Method , instead of run() Method . Never call the thread run Method , call start Method , The system will put run Method as thread execution body , But if you call the thread object directly run Method , be run Method is equivalent to a common method , Execute now , And in run Other threads cannot execute concurrently before the method returns . It's important to point out that , Calling the thread's run After method , The thread is no longer in the new state , So don't call threads anymore start Method ,start Method is only used for threads with new state , Used to make it ready , Wait at any time cpu. If you insist on execution st It's going to explode IllegalThreadStateException It's abnormal .)
Called the thread object start After method , The thread immediately enters the ready state – The ready state is equivalent to waiting for execution , But the thread did not really enter the running state . If you want to call the sub thread start If the sub thread executes immediately after the method , The program can use Thread.sleep(1) Method , Let the currently running thread , That is, the main thread sleeps 1 millisecond , cracking , But within this millisecond cpu I won't be idle , He will execute another thread in the ready state , So it's obviously just start The thread of , In this way, the sub thread can execute immediately .
Operation and blocking status
In the following cases , The thread will enter a blocking state :
- I called sleep Self blocking
- The thread wants to get a synchronization lock , But this lock is held by other threads and is not released
- Thread called a blocking type IO Method , Before the method returns , The thread is blocked .
- The thread is waiting for a notification notify
- The program calls the thread's suspend Method to suspend a thread , But this method is easy to cause deadlock , This method should be avoided as much as possible .
When the executing thread is blocked , Other threads can get execution opportunities . The blocked thread will re-enter the ready state at the right time , Note that the ready state is not the running state . It would also mean , After the blocked thread is unblocked , You must wait for the thread scheduler to call it again .
Ways to unblock
For the above situations, when the following specific situations occur, the above blocking can be removed , Let the thread enter the ready state again :
- call sleep It's causing a lot of congestion , After the specified time, you can enter the ready state
- Using blocking IO Blocking caused by method , When that method returns, the blocking will be removed .
- The thread successfully obtained the synchronization lock it tried to get .( Synchronization monitor )
- While the thread is waiting for notification , Other threads sent this notice .
- Calling thread's suspend() Method to suspend the thread , Is called the resdme() Method .

It can be seen from the picture that
- When a thread is blocked , His trend can only be to become ready . It cannot be directly changed into the running state . The transition between ready state and running state is usually not controlled by the program , It is determined by the system thread scheduling .
- When the thread in the ready state obtains the processing power of the processor, it enters the running state
- When a running thread loses processor rights ( Blocked ) The thread will enter the blocking state ! But there is an exception to this method , call yield() Method words , The running thread can be directly transferred to the ready state . Later yield() This method .
Thread death
The thread will end in the following three states , At the end of it, I was in a state of death :
- run() Method perhaps call() Method execution complete , Thread ends normally .
- The thread threw an uncapped exception
- Call the thread's stop() Method to end the thread , This method can easily lead to deadlock , It is usually not recommended to use . What is a deadlock ?
Simple example of thread life cycle
repeat start() The tragedy caused by threads
When the main thread ends , Other threads are not affected , It won't end with it . Once the sub thread is started , He has the same status as the main thread , He will not be affected by the main thread . To test whether a thread has died , You can call the thread object isAlive() Method , When the thread is ready , Blocking , When running, it will return true, When it is in the state of new creation and death, it will return false.0 also Don't try to call... On a thread that has died start Method makes him restart , Death is death , This thread will not be able to execute as a thread again . mandatory start Would throw exceptions .
/** * Test when a thread dies , If I open again start Method , Is it feasible? ? */
public void testRestarThread(){
Thread1 thread1 = new Thread1(); // At this time, the thread is in the new state
for (int i = 0; i < 300; i++) {
System.out.println(Thread.currentThread() + "------ i = " + i);
if (i == 20) {
thread1.start();// The thread is in a ready state
}else if (i > 40){
// In this case , It is estimated that thread1 It's dead
if (!thread1.isAlive()) {
// When the thread is ready , function , And blocking state, this judgment method will return true
thread1.start();// If the thread dies , Just try to drive in this unreasonable way
}
}
}
}
class Thread1 extends Thread{
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread() + "");
// Run out run The logic inside is finished , Thread end , Death
}
}
Running results :
Thread[main,5,main]------ i = 0
Thread[main,5,main]------ i = 1
Thread[main,5,main]------ i = 2
Thread[main,5,main]------ i = 3
Thread[main,5,main]------ i = 4
Thread[main,5,main]------ i = 5
Thread[main,5,main]------ i = 6
Thread[main,5,main]------ i = 7
Thread[main,5,main]------ i = 8
Thread[main,5,main]------ i = 9
Thread[main,5,main]------ i = 10
Thread[main,5,main]------ i = 11
Thread[main,5,main]------ i = 12
Thread[main,5,main]------ i = 13
Thread[main,5,main]------ i = 14
Thread[main,5,main]------ i = 15
Thread[main,5,main]------ i = 16
Thread[main,5,main]------ i = 17
Thread[main,5,main]------ i = 18
Thread[main,5,main]------ i = 19
Thread[main,5,main]------ i = 20
Thread[main,5,main]------ i = 21
Thread[main,5,main]------ i = 22
Thread[main,5,main]------ i = 23
Thread[main,5,main]------ i = 24
Thread[main,5,main]------ i = 25
Thread[main,5,main]------ i = 26
Thread[main,5,main]------ i = 27
Thread[main,5,main]------ i = 28
Thread[Thread-0,5,main]
Thread[main,5,main]------ i = 29
Thread[main,5,main]------ i = 30
Thread[main,5,main]------ i = 31
Thread[main,5,main]------ i = 32
Thread[main,5,main]------ i = 33
Thread[main,5,main]------ i = 34
Thread[main,5,main]------ i = 35
Thread[main,5,main]------ i = 36
Thread[main,5,main]------ i = 37
Thread[main,5,main]------ i = 38
Thread[main,5,main]------ i = 39
Thread[main,5,main]------ i = 40
Thread[main,5,main]------ i = 41
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at Thread.ThreadDemo.testRestarThread(ThreadDemo.java:15)
at Thread.ThreadDemoControlTool.main(ThreadDemoControlTool.java:10)
Throw abnormal ,start You can't drive casually .
Thread priority
JVM Thread scheduling adopts priority based preemptive scheduling mechanism , Thread always has priority , And the priority range is 1 To 10 Between . in the majority of cases , The priority of the thread running at the front line will be greater than or equal to the priority of any thread in the thread pool . But this is only the case in most cases .
Be careful : When designing multithreaded applications , Be sure not to depend on the priority of the thread . Because the thread scheduling priority operation is not guaranteed , Thread priority can only be used as a way to improve program efficiency , But make sure that the program does not rely on this operation .
When the threads in the thread pool are lost, they all have the same priority , The scheduler's JVM The implementation is free to choose the thread it likes . At this time, the calling program may operate in two ways , One is to select a thread , Until it blocks or runs . Second, time slice , Provide equal opportunities for each thread in the thread pool .
Set the priority of the thread : The default priority of a thread is to follow the priority of the thread that created it , That is, whoever brings it out is up to him . We can go through setPriority(int priority) Change the priority of a thread . for example :
Thread t = new MyThread();
t.serPriority(8);
t.start();
The priority of the thread is 1 To 10 Integer between ,JVM Does not change the priority of a thread . However 1 To 10 There is no guarantee of the value between . some JVM May not recognize 10 Different values , And merge these priorities every two or more , Become less than 10 Priority , Then two or more priority threads can be mapped to one priority . The default priority of a thread is 5,Thread There are three constants in the class , Define the priority range of the thread .
static int MAX_PRIORITY // Threads can have the highest priority
static int MIN_PRIORITY // Threads have the lowest priority
static int NORM_PRIORITY // The default priority assigned to a thread
边栏推荐
- Leetcode's 302 weekly rematch
- Efficientformer: lightweight vit backbone
- Proxy
- 基于Kubernetes v1.24.0的集群搭建(三)
- 如何用WebGPU流畅渲染百万级2D物体?
- cookie
- 如何使用autofs挂载NFS共享
- 权限系统就该这么设计,yyds
- What kind of experience is a monthly salary of 30000 yuan? Can we achieve this level as we media
- [datasheet] interpretation of cs5480 data book of metering chip
猜你喜欢

Okaleido tiger NFT is about to log in to binance NFT platform

Wechat applet generates QR code
![[rust] reference and borrowing, string slice type (& STR) - rust language foundation 12](/img/48/7a1777b735312f29d3a4016a14598c.png)
[rust] reference and borrowing, string slice type (& STR) - rust language foundation 12
How to render millions of 2D objects smoothly with webgpu?

34. Add two numbers

Summary of recent interviews
![[datasheet phy] interpretation of ksz8081 data manual](/img/14/cca728ebb9baea9d937b82bfb11725.png)
[datasheet phy] interpretation of ksz8081 data manual

Leetcode's 302 weekly rematch

English语法_不定代词 - 概述

Reserved instances & Savings Plans
随机推荐
微信小程序生成二维码
29. Right view of binary tree
Is it safe to contact the account manager online to open a fund account?
高速成长的背后,华为云乌兰察布数据中心的绿色之道
让一套代码完美适配各种屏幕
月薪 3万人民币是一种怎样的体验?做自媒体可以达到这种水平吗
Localstorage
Use abp Zero builds a third-party login module (4): wechat applet development
手把手教你用 Power BI 实现 4 种可视化图表
国产旗舰手机定价近六千,却连iPhone12都打不过,用户选谁很明确
[datasheet] interpretation of cs5480 data book of metering chip
基于matlab的声音识别
[rust] reference and borrowing, string slice type (& STR) - rust language foundation 12
class
基于Kubernetes v1.24.0的集群搭建(三)
3. Realize snake and basic game interface
QT based software framework design
6-16 vulnerability exploitation -rlogin maximum permission login
Is there a free and commercially available website for US media video clips?
Solutions to problems in IE6 browser