The following code leads to java.lang.IllegalThreadStateException: Thread already started
when I called start()
method second time in program.
updateUI.join(); if (!updateUI.isAlive()) updateUI.start();
This happens the second time updateUI.start()
is called. I've stepped through it multiple times and the thread is called and completly runs to completion before hitting updateUI.start()
.
Calling updateUI.run()
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.
No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.
PS: Even a thread is done, we can't use the same object (thread id) second time. Until or unless the JVM is reuse that id.
In exactly the same way you would call the method once. You simply have as many statements calling the method as your code requires. So if I have a method to print a string, e.g.: public void printString(String text) {
The answer for this is know one thread can run only once . if you try to run the same thread twice it will execute for the first time but will give error for second time and the error will be IllegalThreadStateException .
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.
Furthermore:
Throws:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With