Stop thread and again start giving IllegalThreadStateException in blackberry

AnkitRox picture AnkitRox · Nov 24, 2012 · Viewed 13.4k times · Source

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?

Answer

Nate picture Nate · Nov 24, 2012

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();

From the API docs

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.