当前位置:网站首页>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.
边栏推荐
- What is the London Silver unit
- Leetcode 724. 寻找数组的中心下标(可以,一次过)
- 每日3题(2):检查二进制字符串字段
- AbortController的使用
- 隱私計算FATE-離線預測
- Elegant custom ThreadPoolExecutor thread pool
- [PHP code injection] common injectable functions of PHP language and utilization examples of PHP code injection vulnerabilities
- Li Kou's 81st biweekly match
- Redis persistence
- 優雅的自定義 ThreadPoolExecutor 線程池
猜你喜欢

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

基于 Nebula Graph 构建百亿关系知识图谱实践

【业务安全-01】业务安全概述及测试流程
![[business security-02] business data security test and example of commodity order quantity tampering](/img/0f/c4d4dd72bed206bbe3e15e32456e2c.png)
[business security-02] business data security test and example of commodity order quantity tampering

Unity3d best practices: folder structure and source control

Interview question: rendering 100000 data solutions

CAS之比较并交换

Use GCC to generate an abstract syntax tree "ast" and dump it to Dot file and visualization

原子操作类

基于Vue+Node+MySQL的美食菜谱食材网站设计与实现
随机推荐
[xman2018 qualifying] pass
跨境电商多商户系统怎么选
Make a ThreadLocal (source code) that everyone can understand
做一篇人人能搞懂的ThreadLocal(源码)
Volatile and JMM
Naacl 2022 | TAMT: search the transportable Bert subnet through downstream task independent mask training
Design and implementation of food recipe and ingredients website based on vue+node+mysql
2022-06-27日报:Swin Transformer、ViT作者等共话:好的基础模型是CV研究者的朴素追求
【高等数学】从法向量到第二类曲面积分
AQS Abstract queue synchronizer
優雅的自定義 ThreadPoolExecutor 線程池
Maximum profit of stock (offer 63)
Redis persistence
Pycharm安装与设置
Design skills of main function of Blue Bridge Cup single chip microcomputer
PR second training notes
Handling methods for NVIDIA deepstream running delay, jamming and crash
[business security-02] business data security test and example of commodity order quantity tampering
Fundamentals of software engineering (I)
Buuctf Misc