当前位置:网站首页>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.
边栏推荐
- 2022-06-27日报:Swin Transformer、ViT作者等共话:好的基础模型是CV研究者的朴素追求
- Integration of entry-level SSM framework based on XML configuration file
- 巧用redis实现点赞功能,它不比mysql香吗?
- 基于 Nebula Graph 构建百亿关系知识图谱实践
- CAS comparison and exchange
- Practice of constructing ten billion relationship knowledge map based on Nebula graph
- CCID Consulting released the database Market Research Report on key application fields during the "14th five year plan" (attached with download)
- PostgreSQL 15新版本特性解读(含直播问答、PPT资料汇总)
- 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
- PR second training notes
猜你喜欢

What kind of experience is it to read other people's code

【业务安全-01】业务安全概述及测试流程

Privacy computing fat offline prediction

QT 如何在背景图中将部分区域设置为透明

volatile与JMM

Teach you how to realize pynq-z2 bar code recognition

基于WEB平台的阅读APP设计与实现

【微服务|Sentinel】热点规则|授权规则|集群流控|机器列表

Getting to know cloud native security for the first time: the best guarantee in the cloud Era

Design and implementation of food recipe and ingredients website based on vue+node+mysql
随机推荐
About sitemap XML problems
关于 Spartacus 的 sitemap.xml 问题
Design and implementation of reading app based on Web Platform
[advanced mathematics] from normal vector to surface integral of the second kind
基于WEB平台的阅读APP设计与实现
Redis CacheClient
Teach you how to realize pynq-z2 bar code recognition
反射学习总结
All you want to know about large screen visualization is here
Resolve activity startup - lifecycle Perspective
跨境电商多商户系统怎么选
海量数据!秒级分析!Flink+Doris构建实时数仓方案
E-week finance Q1 mobile banking has 650million active users; Layout of financial subsidiaries in emerging fields
【高等数学】从法向量到第二类曲面积分
PostgreSQL 15新版本特性解读(含直播问答、PPT资料汇总)
Design skills of main function of Blue Bridge Cup single chip microcomputer
At a time of oversupply of chips, China, the largest importer, continued to reduce imports, and the United States panicked
Getting to know cloud native security for the first time: the best guarantee in the cloud Era
Teach you how to package and release the mofish Library
机械硬盘和ssd固态硬盘的原理对比分析