Will Will - 1 year ago 75
Android Question

Is it legal to call the start method twice on the same Thread?

The following code leads to "java.lang.IllegalThreadStateException: Thread already started." the second time it is run through on the program.


if (!updateUI.isAlive())

This happens the second time
is called. I've stepped through it multiple times and the thread is called and completly runs to completion before hitting

avoids the error but causes the thread to run in the UI thread (the calling thread, as mentioned in other posts on SO), which is not what I want.

Can a Thread be started only once? If so than what do I do if I want to run the thread again? This particular thread is doing some calculation in the background, if I don't do it in the thread than it's done in the UI thread and the user has an unreasonably long wait.

Answer Source

From the Java API Specification for the Thread.start method:

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.


IllegalThreadStateException - if the thread was already started.

So yes, a Thread can only be started once.

If so than what do I do if I want to run the thread again?

If a Thread needs to be run more than once, then one should make an new instance of the Thread and call start on it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download