问题描述
伙计们
我知道这里曾有人问过这个问题,尽管是间接的.但这并没有回答我的疑问.
问题:在同一线程上两次调用start方法?
I know this question has been asked before here, though indirectly. But it didn't answer my doubt.
Question : Is it legal to call the start method twice on the same Thread?
从规范,
我同意.但是我的代码没有抛出 IllegalThreadStateException
可能会在执行以下程序时抛出该错误.
I agree. But my code doesn't throw a IllegalThreadStateException
which it is expected to throw on execution of following program.
public class Tester extends Thread {
public void run() {
System.out.print("run");
}
public static void main(String[] args) {
Tester thread = new Tester();
new Thread(thread).start();
new Thread(thread).start();
}
}
Q.1)我在Eclipse中运行了以上代码.在这里,由于我试图在同一实例上启动新线程,因此预计会抛出IllegalThreadStateException
.但事实并非如此.
Q.1) I ran the above code in Eclipse. Here, since I am trying to start a new thread on the same instance, a IllegalThreadStateException
is expected to be thrown. But it doesn't.
为什么?
Q.2)如果我们确实确实在同一实例上启动了一个新线程,那会带来什么危害?
任何帮助将不胜感激!
推荐答案
首先,您要调用两个不同的线程对象,即:
Firstly, you are invoking on two different thread objects ie:
new Thread(thread).start();
new Thread(thread).start();
您正在两个不同的实例上调用start方法.出于这个原因,您没有得到例外.
you are calling start method on two different instances. for which reason you are not getting the exception.
尝试以下操作以获取异常
try with following to get the exception
thread.start();
thread.start();
这篇关于Java-Java线程调用可以多次启动吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!