当前位置:网站首页>[processes and threads]
[processes and threads]
2022-06-23 11:41:00 【Word duck】
Catalog
How to transfer the process state
parallel (parallel) and Concurrent (concurrent)
User mode (user space) and Kernel mode (kernel space)
Execution flow (executionflow)
The main research problems of memory management
Process of communication IPC(Inter Process Communication)
Common ways of interprocess communication
(2) process (process) And thread (thread) The relationship between
(3) Why? OS To introduce thread This concept .
(4) The difference between threads and processes
Method 1 : Inherit Thread class
Method 2 : Realization Runnable Interface
How to understand t.start() What did you do ?
The relationship between thread and method call stack
Understand stacks and stack frames
Thread Common properties and methods of
(4) Get current thread reference ——Thread.currentThread()
(5) Let the thread out CPU——yield( )
Foreground thread and background thread
JDK The self-contained tool for observing threads in ——jconsole
Five states of process
- newly build : The process is in the process of being created
- be ready : Everything has , Only owe CPU
- function : The instructions of the process are really CPU running
- Blocking : The process is waiting for an external condition , So I can't continue for the time being
- end : The execution of all instructions of the process ends , but PCB For the time being ,OS When some other work needs to be done
Process state transition diagram :

All operating states must be changed from ready state , Because of the process CPU Must go through OS System allocation can get .
How to transfer the process state
- -> newly build : As the program starts running
- newly build -> be ready : The initialization of the process is complete , The work is done by OS The instructions are complete
- be ready -> function : The process is OS Choose , And assigned CPU after
- function -> end : The execution of the last instruction of the process ends , It can be roughly understood as main Method execution is over
- function -> be ready : 1. Preempted by a high priority process ;2. The time slice runs out ;3. The process can perform some OS System call provided , Give up on your own initiative
- function -> Blocking : Wait for some external conditions , Wait for I0 equipment ; The process sleeps for a period of time
- Blocking -> be ready : External conditions meet , Such as I0 Here comes the data 、 It's time to sleep ...
- end -> : process PCB Be completely OS Recycled
At the same time , There is more than one process in different states . In New 、 be ready 、 jam 、 There can be more than one end state , But mononuclear cpu Under the circumstances , There can only be one running state at the same time .
OS How to switch processes
Switch through context : Protect the context of the previous process + Restore the context of the next process
Context : With PC The value in a set of registers represented by a register .
Protect context : Put the value in the register , Save to a location in memory . Restore context : Put the previously protected value in memory , Write to register
parallel (parallel) and Concurrent (concurrent)
parallel : The process is really executing at the same time , At the same time from the microscopic point of view , There are multiple instructions executing , So it will only be more CPU In a multi-core scenario
Concurrent : The process is executing at the same time , On the micro , It shows that only one process is executed at a time , But macroscopically , Multiple processes are “ meanwhile " perform
User mode (user space) and Kernel mode (kernel space)
When CPU What is being carried out is OS When instructed by , It is considered to enter the kernel state . conversely , When an instruction of an ordinary process is being executed , In user mode . Kernel state instruction permissions are high , Basically all hardware can be accessed ; The command permission of user status is low , Only access OS Specified resources . This is because CPU It has permission switch . Generally speaking , The performance of user mode is better , The performance of kernel state is poor .
Execution flow (executionflow)
Each execution flow has its own pc A set of instructions , Different execution flows appear to be completely independent from the phenomenon .
memory management
and cpu Different ,cpu Pay more attention to the division of time , The allocation of memory resources by the operating system , It's using Spatial patterns —— Different processes use different areas of memory , They don't interfere with each other .
Memory is roughly divided into : The memory used by the kernel 、 Memory allocated to ordinary processes 、 Free space . Note that spatial partitioning is not guaranteed to be continuous .
The main research problems of memory management
- Manage which memory has been allocated , Which memory has not been allocated temporarily
- Memory allocated , When to recycle 、 How to recycle
- Physical address and linear address translation
- Memory fragments
Process of communication IPC(Inter Process Communication)
In theory, the process is independent , But in practice, many processes often cooperate with each other , To complete complex work . because OS Resource allocation is based on the process , Including memory . Assigned to A The memory of the process will not be allocated to B process . therefore , process A、B There is no possibility of data exchange directly through memory . therefore OS Need to provide a mechanism , Used to make A、B Necessary data exchange between processes - inter process communication .
Common ways of interprocess communication
- The Conduit (pipe)
- Message queue (message queue)
- Semaphore (semaphore)
- The signal (signal)
- Shared memory (shared memory)
- The Internet (network)
Threads (Thread)
Concept
(1) What is thread
Thread is OS To schedule ( Distribute CPU) The basic unit of . A thread is a " Execution flow ". Each thread can execute its own code according to the sequence . Between multiple threads " meanwhile " Execute Multiple codes .
(2) process (process) And thread (thread) The relationship between
Process and thread are one to many relationships . A thread must belong to a process ; Multiple threads are allowed in one process .
There is at least one thread in a process , It is usually used by this thread that exists from the beginning , Called the main thread (main thread). The status between the main thread and other threads is completely equal , There's nothing special about it .
(3) Why? OS To introduce thread This concept .
Because the concept of process is inherently resource isolated , Therefore, data communication between processes is bound to be a high-cost work .
In reality , A task needs multiple execution flows to complete together , It's very common . therefore , A concept of execution flow is needed to facilitate data communication , Threads assume this responsibility .
(4) The difference between threads and processes
- A process is the smallest unit of resource allocation , A thread is the smallest unit of program execution ( The smallest unit of resource scheduling )
- Processes contain threads , At least one thread per process exists , The main thread .
- Process has its own independent address space , Every time a process is started , The system will allocate address space for it , Create data tables to maintain code snippets 、 Stack and data segments , This operation is very expensive . Threads share the data in the process , Use the same address space , therefore CPU Switching a thread costs much less than a process , At the same time, the cost of creating a thread is much smaller than that of a process .
- There is no shared memory space between processes ., Threads of the same process share the same memory space . Easier communication between threads , Threads sharing global variables in the same process 、 Data such as static variables , And the communication between processes needs to be in the form of communication (IPC) Conduct .
- Multiprocessing programs are more robust , A multithreaded program only needs one thread to die , The whole process is dead , And the death of one process does not affect the other , Because the process has its own address space .
Thread creation
Method 1 : Inherit Thread class
Custom thread class inheritance Thread class
rewrite run() Method , Write thread executor
Creating thread objects , call start() Method to start the thread
public class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("good"+i);
}
}
public static void main(String[] args) {
// The main thread
MyThread myThread = new MyThread();
// At the same time , The main thread and the above thread execute at the same time
myThread.start();
for (int i = 0; i < 200; i++) {
System.out.println(" I'm learning "+i);
}
}
}Running results :
You can see that the main thread and the above thread execute at the same time .
Method 2 : Realization Runnable Interface
Definition MyRunnable Class implementation Runnable Interface
Realization run() Method , Write thread executor
establish Threads object
establish Thread Class object , take Runnable Object as parameter , call start() Method
public class MyThread_II implements Runnable{
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("good"+i);
}
}
public static void main(String[] args) {
// establish runnable Implementation class object of interface
MyThread_II myThread = new MyThread_II();
// Creating thread objects , Opening a thread through a thread object ( agent )
Thread thread = new Thread(myThread);
//Thread thread = new Thread(new MyThread_II());
thread.start();
}
}Compare the above two methods :
- Inherit Thread class , Use it directly this It represents the reference of the current thread object .
- Realization Runnable Interface ,this It means MyRunnable References to , Need to use Thread.currentThread()
How to understand t.start() What did you do ?
t.start() Only one thing has been done : Change the state of the thread from new to ready . That is, it is not responsible for distribution CPU.
The thread adds to the ready queue of the thread scheduler , Waiting to be selected by the scheduler to allocate CPU. From the moment the child thread enters the ready queue , The child thread and the main thread are completely equal in status .
therefore , Which thread is selected to allocate CPU, You are completely resigned to fate . It is theoretically possible to execute the statements in the child thread or the main thread first . This is why we see the main thread and the custom thread executing alternately .
Observe the results of the first thread we created , The probability is that the printing in the main thread is executed first , It means that two threads have equal status ?
t.start() Is the statement in the main thread . In other words , This statement is executed , The main thread is now CPU On .( Main thread running state ), therefore , The main route has just been executed t.start() The probability of thread scheduling occurring immediately is not high , So the probability is still t.start() The next statement of is executed first .
distinguish start() and run()
Don't use it incorrectly run() Method , Using this method will be executed first , And in the main thread , Is a simple method call .
Use start():
public class MyThread extends Thread{
@Override
public void run() {
System.out.println(" I am a "+Thread.currentThread().getName());
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
// The main thread
System.out.println(" I am a "+Thread.currentThread().getName());
}
}
// Output :
I am a main
I am a Thread-0Use run():
public class MyThread extends Thread{
@Override
public void run() {
System.out.println(" I am a "+Thread.currentThread().getName());
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.run();
// The main thread
System.out.println(" I am a "+Thread.currentThread().getName());
}
}
// Output :
I am a main
I am a mainWhatever we write is Thread The subclass of is still Runnable Implementation class of , Just for the thread to start “ Program ”. therefore , The same procedure , You can start multiple threads .
Example :
public class MyThread extends Thread{
@Override
public void run() {
System.out.println(" I am a " + Thread.currentThread().getName());
System.out.println(" my id yes " + Thread.currentThread().getId());
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
MyThread t2 = new MyThread();
t2.start();
MyThread t3 = new MyThread();
t3.start();
MyThread t4= new MyThread();
t4.start();
}
}Output :
Be careful : The result of each output is not fixed
The relationship between thread and method call stack
Each thread has its own call stack
public class Add {
public static int add(int a,int b){
return a + b;
}
}
public class MyThread extends Thread{
@Override
public void run() {
System.out.println(Add.add(5,5));
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
// Call yourself in the main thread add Method
System.out.println(Add.add(10, 20));
}
}
Set a breakpoint , The right choice Thread. Each line of the method call stack seen in the debugger is a stack frame (frame), What is saved is the temporary data when the method is run , The most important thing for us is the local variable .

Since each thread is an independent execution flow ,A Which methods have been called , and B It doesn't matter at all . Each thread has its own independent stack . The above is the main thread , The drop-down box allows you to select another thread


According to procedure = Instructions + data , Here we call the same method , It indicates that the same batch of instructions are executed —— Add two numbers and return
Because the stack is different ( Different frames ) : Description when executing instructions , The data to be processed is different . Therefore, the main thread and sub thread can be independently , debug , The two do not affect each other .
Understand stacks and stack frames
Without multithreading and external input , The running of a program is actually a state machine

During a function call , A new state will be created , The final returned result is still the original state , Only the data has changed

If multiple nested calls occur , Like this :
You can see , The order in which these boxes appear is First in, then out therefore , We can use the stack to maintain these boxes .
Stack : The current moment of the current execution flow ( When the time stops ) What are the status boxes for ( Call order of real methods )
box : Stack frame (frame) What is installed is some temporary data needed to run the method ( The main thing is to have variables )
Thread Common properties and methods of
(1) Common properties
| attribute | Access method |
| ID | getId() |
| name (name) | getName() |
| state | getState() |
| priority | getPriority() |
| Background thread or not | isDaemon() |
| Survival | isAlive() |
| Whether it is interrupted | isInterrupted() |
- This process (JVM process ) Unique for internal distribution , Can only get You can't set
- By default , If no thread name is given , Thread names follow Thread-..; The first is Thread-0、Thread-1、 Thread-2, The main thread defaults to main. Sure get It's fine too set, It can also be repeated
- Status indicates the current situation of the thread
- Threads with higher priority are theoretically easier to schedule to . Threads can also set Your priorities , But be careful , Priority setting , Just for JVM Some suggestions , You cannot force which thread to schedule first . The lowest priority is 1 , Up to 10, The default is 5
- About background threads , Need to remember a little :JVM After all non background threads of a process end , Will end the operation .
- Survival , That is, simple understanding , by run Whether the method has finished running Thread interrupt problem
Set up name:
public class SetNameThread extends Thread{
// Method 1
// public SetNameThread(){
// setName(" I am Zhang San. ");
// }
// Method 2
// public SetNameThread() {
// super(" I am Zhang San. "); // Call the parent class (Thread) Construction method of
// }
@Override
public void run() {
System.out.println(this.getName());
}
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
SetNameThread t1 = new SetNameThread();
// Method 3
t1.setName(" I am a t1");
t1.start();
SetNameThread t2 = new SetNameThread();
t2.setName(" I am a t2");
t2.start();
}
}Or you can create a parameterized construct to set the name :
public class SetNameThread extends Thread{
public SetNameThread(String name){
super(name);
}
@Override
public void run() {
System.out.println(this.getName());
}
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
SetNameThread t1 = new SetNameThread(" I am a t1");
t1.start();
SetNameThread t2 = new SetNameThread(" I am a t2");
t2.start();
}
}Method 1 above 、 Second, this class sets the thread names to be consistent .
(2) Wait for a thread -join()
Sometimes , We need to wait for a thread to finish its work , In order to carry out their next work . for example ,A Go to a restaurant for dinner , Found no wallet , So let B Go home and get your wallet , that A You have to wait B You can check out and leave after you bring your wallet .
public class Main {
private static class B extends Thread {
@Override
public void run() {
// simulation B It takes a long time
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
println("B say : My task has been completed ");
}
}
private static void println(String msg) {
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(format.format(date) + ": " + msg);
}
public static void main(String[] args) throws InterruptedException {
B b = new B();
b.start();
println("A Go to dinner by yourself ");
b.join();
println("A say :B Send me the money , Check out and leave ");
}
}
// Output :
2022-06-21 17:34:46: A Go to dinner by yourself
2022-06-21 17:34:51: B say : My task has been completed
2022-06-21 17:34:51: A say :B Send me the money , Check out and leave You can find , It must be waiting B After I got my wallet A You can still check out and leave . Use b.join(); after , The current thread will block , until B Only after the operation is completed will it return to , This is the time B It must be over .
meanwhile join Methods also have overloaded forms :
- join(long millis) Wait for the thread to die , But wait at most millis millisecond
- join(long millis, int nanos) The time unit is more accurate
(3) Sleep the current thread
- TimeUnit.SECONDS.sleep( Number of seconds );—— In seconds
- Thread.sleep( Number of seconds );—— In Milliseconds
Let the thread sleep , Is to make the current thread from function -> Blocking , Wait for the required time to pass , The thread from Blocking -> be ready
(4) Get current thread reference ——Thread.currentThread()
public class Main {
public static void main(String[] args) {
Thread thread = Thread.currentThread();
System.out.println(thread.getName());
}
}
// Output :main(5) Let the thread out CPU——yield( )
Change the thread from running state to ready state
public class YieldTest extends Thread{
@Override
public void run() {
while (true){
System.out.println(" I am a "+Thread.currentThread().getName());
}
}
public static void main(String[] args) {
YieldTest t1 = new YieldTest();
t1.setName(" Zhang San ");
YieldTest t2 = new YieldTest();
t2.setName(" Li Si ");
t1.start();
t2.start();
}
}By observing the running results, we can see that the probability of two threads is almost the same , If this time , Li Si is dignified , Choose give up CPU, Let's see what happens
public void run() {
while (true){
System.out.println(" I am a "+Thread.currentThread().getName());
if(Thread.currentThread().getName().equals(" Li Si ")){
Thread.yield();
}
}
}After running, we found that , Basically, what is printed is Zhang San , But it is not that lisih did not appear at all .
yield It is mainly used to perform some time-consuming tasks When computing tasks , To prevent the computer from being in “ Carton ” The phenomenon of , Give up some from time to time CPU resources , to OS Other processes in .
(6) Interrupt a thread
Method 1 :deprecate The violence stopped , direct kill Drop thread , At present, it is basically not used . The reason is that I don't know how the thread works
Method 2 :interrupt();A Want to make B stop it ,A to B Take the initiative to send a signal ,B For a while , After seeing the stop signal , You can take the initiative , Finish the task at hand in one stage , Take the initiative to quit .
that B How to sense that someone has made it stop :
- adopt interrupted() Method , Check whether the current thread is terminated ,true: Someone told us to stop false: No one told us to stop
- B May be asleep ,JVM The way to deal with it is , In the form of an exception , notice B : InterruptedException
it is to be noted that ,B Do you want to stop , When does it stop , How to stop , It's up to you
State of thread
- NEW: Arranged work , We haven't started yet
- RUNNABLE: Working , It can also be divided into working and about to start working .
- BLOCKED: Waiting in line for something else
- WAITING: Waiting in line for something else
- TIMED_WAITING: Waiting in line for something else
- TERMINATED: The work is done

Thread state can only be obtained , Cannot set .
Foreground thread and background thread
The foreground thread usually does one - Some have interactive work , Background thread is also called spirit thread or daemon thread , It is usually a Some working threads .
such as : A music player 1. The thread responds to user clicks ( The front desk )2. Threads go to the network to download songs ( backstage )
it is to be noted that : When all foreground threads exit ,JVM The process exits , Even if the background thread is still working , Also exit normally
JDK The self-contained tool for observing threads in ——jconsole
This tool can be used to observe JVM Some relevant situations during operation , For example, memory. 、 Class loading 、 Thread situation

Found after opening idea The name of the thread started , Double click in , You can observe .

边栏推荐
猜你喜欢

Esp32-cam, esp8266, WiFi, Bluetooth, MCU, hotspot create embedded DNS server

Comment Huawei Cloud réalise l'architecture mondiale de réseau audio - vidéo en temps réel à faible latence

16路HD-SDI光端机多路HD-SDI高清视频光端机16路3G-SDI高清音视频光端机

【进程和线程】

@黑马粉丝,这份「高温补贴」你还没领?

攻防演练合集 | 3个阶段,4大要点,蓝队防守全流程纲要解读
[email protected] HDMI2.0光端机 HDMI高清视频光端机"/>4K-HDMI光端机1路[email protected] HDMI2.0光端机 HDMI高清视频光端机

Mysql, how to calculate the maximum value using stored procedures

The country has entered the main flood season. The Ministry of transport: the lines that do not meet the conditions for safe operation will be resolutely shut down!

基本数据类型和对应的包装类
随机推荐
网上注册股票开户很困难么?现在网上开户安全么?
Gary Marcus发文:AI研究者需要知道的三个来自语言学家的观点
坚持五件事,带你走出迷茫困境!
理财产品的赎回时间有规定吗?
Video data annotation tools and platforms (data annotation company)
过采样系列一:采样定理与过采样率
【进程和线程】
汉源高科USB2.0光端机USB2.0光纤延长器USB2.0光纤传输器USB2.0接口转光纤
Vone news | wanglian technology empowers the public to enjoy the self-organization management of the chain network, creating an enterprise level alliance Dao
请问连接oracle时,这个version 1.54 是什么的version?
请问,maxcompute执行sql查询有时特别慢是什么原因
Numbers that only appear once < difficulty coefficient > & Yang Hui triangle < difficulty coefficient >
Vous comprenez vraiment la capacité de sortie de LDO!?
【云原生&微服务八】Ribbon负载均衡策略之WeightedResponseTimeRule源码剖析(响应时间加权)
Rancher 2.6 new monitoring QuickStart
Mobile securities account opening transaction? Is it safe to open an account online now?
Redis 入门-第四篇-数据结构与对象-跳跃表
我在佛山,到哪里开户比较好?手机开户安全么?
Meta称英安全法可能“扫描所有私人信息” 或侵犯隐私
64路PCM电话光端机64路电话+2路百兆以太网电话光端机64路电话PCM语音光端机