当前位置:网站首页>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.
边栏推荐
- Synchronized与锁升级
- Tsinghua & Shangtang & Shanghai AI & CUHK proposed Siamese image modeling, which has both linear probing and intensive prediction performance
- 阅读别人的代码,是一种怎样的体验
- About the meaning of the first two $symbols of SAP ui5 parameter $$updategroupid
- Synchronized and lock escalation
- 2022-06-27日报:Swin Transformer、ViT作者等共话:好的基础模型是CV研究者的朴素追求
- Too many requests at once, and the database is in danger
- [PHP code injection] common injectable functions of PHP language and utilization examples of PHP code injection vulnerabilities
- Maximum profit of stock (offer 63)
- R language objects are stored in JSON
猜你喜欢

基于Vue+Node+MySQL的美食菜谱食材网站设计与实现

CCID Consulting released the database Market Research Report on key application fields during the "14th five year plan" (attached with download)

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

Tsinghua & Shangtang & Shanghai AI & CUHK proposed Siamese image modeling, which has both linear probing and intensive prediction performance

直播app运营模式有哪几种,我们该选择什么样的模式?

Redis master-slave replication, sentinel mode, cluster cluster

阅读别人的代码,是一种怎样的体验

ReentrantLock、ReentrantReadWriteLock、StampedLock

做一篇人人能搞懂的ThreadLocal(源码)

Redis 主从复制、哨兵模式、Cluster集群
随机推荐
R language objects are stored in JSON
my. INI file configuration
Make a ThreadLocal (source code) that everyone can understand
反射学习总结
Design skills of main function of Blue Bridge Cup single chip microcomputer
522. 最长特殊序列 II / 剑指 Offer II 101. 分割等和子集
Cannot determine value type from string ‘<p>1</p>‘
Julia1.1 installation instructions
Interpretation of new version features of PostgreSQL 15 (including live Q & A and PPT data summary)
Openssf security plan: SBOM will drive software supply chain security
Semaphore of thread synchronization
【业务安全-01】业务安全概述及测试流程
海外仓知识科普
[advanced mathematics] from normal vector to surface integral of the second kind
[business security 03] password retrieval business security and interface parameter account modification examples (based on the metinfov4.0 platform)
Step by step expansion of variable parameters in class templates
enable_ if
Kyndryl partnered with Oracle and Veritas
Jupiter core error
volatile与JMM