当前位置:网站首页>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-07-02 23:28:00 【Wang Lei】
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();
}
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();
}
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();
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.
It's up to you to judge right and wrong , Disdain is to listen to people , Gain or loss is more important than number .
official account :Java Analysis of the real interview questions
Interview collection :https://gitee.com/mydb/interview
边栏推荐
- 20220527_ Database process_ Statement retention
- Brief introduction of emotional dialogue recognition and generation
- Win11自动关机设置在哪?Win11设置自动关机的两种方法
- 【Redis笔记】压缩列表(ziplist)
- Realize the linkage between bottomnavigationview and navigation
- CDN 加速,需要域名先备案
- Use of recyclerview with viewbinding
- Eight honors and eight disgraces of the programmer version~
- Connexion à distance de la tarte aux framboises en mode visionneur VNC
- BBR encounters cubic
猜你喜欢
实现BottomNavigationView和Navigation联动
What can I do after buying a domain name?
Remote connection of raspberry pie by VNC viewer
BBR 遭遇 CUBIC
Win11启用粘滞键关闭不了怎么办?粘滞键取消了但不管用怎么解决
Yolox enhanced feature extraction network panet analysis
RuntimeError: no valid convolution algorithms available in CuDNN
Redis 过期策略+conf 记录
[live broadcast appointment] database obcp certification comprehensive upgrade open class
Detailed explanation and application of merging and sorting
随机推荐
Static file display problem
【STL源码剖析】仿函数(待补充)
ping域名报错unknown host,nslookup/systemd-resolve可以正常解析,ping公网地址通怎么解决?
Where is the win11 microphone test? Win11 method of testing microphone
详解Promise使用
2016. maximum difference between incremental elements
Tiktok actual combat ~ number of likes pop-up box
"A good programmer is worth five ordinary programmers!"
VIM interval deletion note
Cryptographic technology -- key and ssl/tls
实现BottomNavigationView和Navigation联动
Doorplate making C language
Redis 过期策略+conf 记录
Hisilicon VI access video process
Redis expiration policy +conf record
20220524_数据库过程_语句留档
程序员版本的八荣八耻~
[redis notes] compressed list (ziplist)
【ML】李宏毅三:梯度下降&分类(高斯分布)
Win11自动关机设置在哪?Win11设置自动关机的两种方法