I am getting IllegalThreadStateException
exception when using following code:
I have already started this thread once(by using thread.start()
) and again trying to start it at another place, so used following code:
thread.interrupt();
thread.start();
But thread.start()
is throwing IllegalThreadStateException
.
What should I use to solve it?
Thread
objects are only meant to be started once. If you need to stop/interrupt a Thread
, and then want to start it again, you should create a new instance, and call start()
on it:
thread.interrupt(); // if you need to make sure thread's run() method stops ASAP
thread = new MyThreadSubclass();
thread.start();
IllegalThreadStateException - if the thread was already started.
I know it's not 100% clear that you can't call start()
again, even if you previously called interrupt()
, but that's the way it works.
If you look at the API docs for standard Java, this issue is more clear.