当前位置:网站首页>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
边栏推荐
- Solving ordinary differential equations with MATLAB
- Boost库链接错误解决方案
- Troubleshooting the cause of the crash when STM32 serial port dam receives 253 bytes
- 用matlab调用vs2015来编译vs工程
- 密码技术---分组密码的模式
- 第三方支付功能测试点【杭州多测师_王sir】【杭州多测师】
- Hisilicon VI access video process
- Sword finger offer II 099 Sum of minimum paths - double hundred code
- 基于Pyqt5工具栏按钮可实现界面切换-1
- @How to use bindsinstance in dagger2
猜你喜欢
阿里云有奖体验:如何使用 PolarDB-X
Implementation of VGA protocol based on FPGA
4 special cases! Schools in area a adopt the re examination score line in area B!
What can I do after buying a domain name?
【Redis笔记】压缩列表(ziplist)
What if win11 can't turn off the sticky key? The sticky key is cancelled but it doesn't work. How to solve it
Writing of head and bottom components of non routing components
RuntimeError: no valid convolution algorithms available in CuDNN
How difficult is it to be high? AI rolls into the mathematics circle, and the accuracy rate of advanced mathematics examination is 81%!
面试过了,起薪16k
随机推荐
What experience is there only one test in the company? Listen to what they say
BBR 遭遇 CUBIC
深度剖析数据在内存中的存储----C语言篇
[redis notes] compressed list (ziplist)
万物并作,吾以观复|OceanBase 政企行业实践
Prometheus deployment
抖音实战~点赞数量弹框
【STL源码剖析】仿函数(待补充)
Introduction to the latest plan of horizon in April 2022
2022 latest and complete interview questions for software testing
20220527_ Database process_ Statement retention
golang中new与make的区别
Jinglianwen technology's low price strategy helps AI enterprises reduce model training costs
Getting started with golang: for Range an alternative method of modifying the values of elements in slices
【ML】李宏毅三:梯度下降&分类(高斯分布)
golang入门:for...range修改切片中元素的值的另类方法
解决:exceptiole ‘xxxxx.QRTZ_LOCKS‘ doesn‘t exist以及mysql的my.cnf文件追加lower_case_table_names后启动报错
内网渗透 | 手把手教你如何进行内网渗透
設置單擊右鍵可以選擇用VS Code打開文件
BBR encounters cubic