Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 713
Will Avatar asked Aug 01 '09 01:08

Will


People also ask

Can I call start method in thread twice?

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.

Is it possible to call the same thread twice using the same object?

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.

Can we call a method twice in Java?

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) {

Can a thread be started twice Python?

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 .


1 Answers

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.

like image 142
coobird Avatar answered Sep 24 '22 23:09

coobird