Folks,
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?
From the spec,
It is never legal to start a thread
more than once. In particular, a
thread may not be restarted once it
has completed execution.
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) 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.
Why ?
Q.2) If at all we did start a new thread on the same instance, what harm it would do ?
Any help would be greatly appreciated !
解决方案
Firstly, you are invoking on two different thread objects ie:
new Thread(thread).start();
new Thread(thread).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();
which is fortunately asked by me :)