当前位置:网站首页>Why can't the start method be called repeatedly? But the run method can?
Why can't the start method be called repeatedly? But the run method can?
2022-06-27 14:51:00 【Retirement procedure ape】

When learning threads , Always will be run Methods and start Method confusion , Although the two methods are completely different , But it's hard to tell when you first use it , The reason is that the effect seems to be the same when used for the first time , As shown in the following code :
public static void main(String[] args) {
// Create a thread
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(" Execute thread one ");
}
});
// call run Method
thread.run();
// Create thread 2
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(" Execute thread 2 ");
}
});
// call start Method
thread2.start();
}
Copy code The results of the above procedures are as follows :

As can be seen from the above results , The execution effect of both calls is the same , Can successfully perform the task . however , If when executing the thread , You can see the difference between the two by printing the name of the current thread , As shown in the following code :
public static void main(String[] args) {
// Create a thread
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// Get the current execution thread
Thread currThread = Thread.currentThread();
System.out.println(" Execute thread one , The thread of :" + currThread.getName());
}
});
// call run Method
thread.run();
// Create thread 2
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
// Get the current execution thread
Thread currThread = Thread.currentThread();
System.out.println(" Execute thread 2 , The thread of :" + currThread.getName());
}
});
// call start Method
thread2.start();
}
Copy code The results of the above procedures are as follows :

From the above results we can see that : When calling run When the method is used , In fact, it calls the current main program main To execute the... Of the method body ; And call start Method is to really create a new thread to execute the task .
difference 1
run Methods and start The first difference between methods is : call start The method is to really start a thread to execute the task , And call run Method is equivalent to executing a normal method run, Does not start a new thread , As shown in the figure below :

difference 2
run Methods and start The second difference between methods is :run Methods are also called thread bodies , It contains the specific business code to be executed , When calling run When the method is used , Will be executed immediately run The code in the method ( If the current thread time slice is not used up ); And call start When the method is used , Is to start a thread and set the state of the thread to ready state . That is to say, call start Method , Not immediately executed .
difference 3
because run The method is the ordinary method , Ordinary methods can be called many times , therefore run Methods can be called multiple times ; and start The method is to create a new thread to perform the task , Because threads can only be created once , therefore Their third difference is :run Methods can be called multiple times , and start Method can only be called once . The test code is as follows :
// Create a thread
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// Gets the thread currently executing
Thread currThread = Thread.currentThread();
System.out.println(" Execute thread one , The thread of :" + currThread.getName());
}
});
// call run Method
thread.run();
// Multiple calls run Method
thread.run();
// Create thread 2
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
// Gets the thread currently executing
Thread currThread = Thread.currentThread();
System.out.println(" Execute thread 2 , The thread of :" + currThread.getName());
}
});
// call start Method
thread2.start();
// Multiple calls start Method
thread2.start();
Copy code The results of the above procedures are as follows :

As can be seen from the above results ,run Method can be called multiple times and can be executed normally , And the second call start Method, the program reports an error , Tips “IllegalThreadStateException” Illegal thread status exception .
Why? start Can't be called repeatedly ?
To find the answer to this question , Just look at start Method implementation source code , Its source code is as follows :

from start The first line of the source code implementation , We can get the answer to the question , because start Method in execution , It will first judge whether the current thread state is equal to 0, That is, whether it is in new status NEW, If it is not equal to the new status , Then it will throw “IllegalThreadStateException” Illegal thread status exception , So that's threaded start The reason why methods cannot be called repeatedly . Its execution process is : When the thread calls the first start After method , The state of the thread will change from the new state NEW, To be ready RUNNABLE, Call again start Method ,JVM It will be judged that the current thread is not equal to the new state , To throw out IllegalThreadStateException Illegal thread status exception .
summary
run Methods and start The main differences between methods are as follows :
- The nature of the method is different :run It's a common way , and start Is the way to start a new thread .
- Different execution speeds : call run Method will execute the task immediately , call start The method is to change the state of the thread to the ready state , Not immediately .
- Different call times :run Methods can be called repeatedly , and start Method can only be called once .
start The reason why methods cannot be called repeatedly is , The state of a thread is irreversible ,Thread stay start Made a judgment in the implementation source code of , If the thread is not new NEW, An illegal thread state exception will be thrown IllegalThreadStateException.
边栏推荐
- Tsinghua & Shangtang & Shanghai AI & CUHK proposed Siamese image modeling, which has both linear probing and intensive prediction performance
- Semaphore of thread synchronization
- How to change a matrix into a triple in R language (i.e. three columns: row, col, value)
- What are the operating modes of the live app? What mode should we choose?
- Pycharm安装与设置
- Is there any discount for opening an account now? Is it safe to open an account online?
- The global chip market may stagnate, and China's chip expansion accelerates to improve its self-sufficiency rate against the trend
- [OS command injection] common OS command execution functions and OS command injection utilization examples and range experiments - based on DVWA range
- Teach you how to realize pynq-z2 bar code recognition
- 522. 最长特殊序列 II / 剑指 Offer II 101. 分割等和子集
猜你喜欢

隐私计算FATE-离线预测

原子操作类

Pychart installation and setup

Leetcode 724. 寻找数组的中心下标(可以,一次过)

HTTP Caching Protocol practice

Lei Jun lost another great general, and liweixing, the founding employee of Xiaomi No. 12, left his post. He once had porridge to create Xiaomi; Intel's $5.4 billion acquisition of tower semiconductor

Calcul de la confidentialité Fate - Prévisions hors ligne

volatile与JMM

Using redis skillfully to realize the like function, isn't it more fragrant than MySQL?

Interview question: rendering 100000 data solutions
随机推荐
Getting to know cloud native security for the first time: the best guarantee in the cloud Era
Leetcode 724. Find the central subscript of the array (yes, once)
事务的四大特性
Notes learning summary
Teach you how to realize pynq-z2 bar code recognition
Abnormal analysis of pcf8591 voltage measurement data
Brief reading of dynamic networks and conditional computing papers and code collection
【高等数学】从法向量到第二类曲面积分
[WUSTCTF2020]girlfriend
AbortController的使用
Lei Jun lost another great general, and liweixing, the founding employee of Xiaomi No. 12, left his post. He once had porridge to create Xiaomi; Intel's $5.4 billion acquisition of tower semiconductor
Redis CacheClient
Pychart installation and setup
Interpretation of new version features of PostgreSQL 15 (including live Q & A and PPT data summary)
Redis CacheClient
How is the London Silver point difference calculated
易周金融 | Q1手机银行活跃用户规模6.5亿;理财子公司布局新兴领域
At a time of oversupply of chips, China, the largest importer, continued to reduce imports, and the United States panicked
每日3题(1):找到最近的有相同 X 或 Y 坐标的点
How to change a matrix into a triple in R language (i.e. three columns: row, col, value)