Can I start the stream again after his death?

If I use start () for the Thread object and the run () method returns, can I call start () again?

eg,

MyThread myThread = new MyThread(); myThread.start(); // run method executes and returns in 2 seconds // sleep for 5 seconds to make sure the thread has died myThread.start(); 

I'm just curious because my code throws IllegalThreadStateExceptions, so I want to know if that is because you cannot do the above.

+6
java multithreading
source share
5 answers

No, you can’t. And the Javadoc for the Thread.start() method tells you that!

+11
source share

From the comment:

Is there anything else you can do to restart the stream?

You can use ThreadPoolExecutor , which will allow you to perform tasks and let the service assign a thread to the task. When the task is completed, the thread is idle until it receives the next task.

So, you do not restart the thread, but you will repeat / resume the task.

+4
source share

Nope.

From Javadoc for java.lang.Thread :

You cannot start a thread more than once.

0
source share

From javadoc:

You cannot start a thread more than once. In particular, the thread cannot be restarted and completed execution.

See Thread.start () javadoc for more details.

There are other ways to achieve what you are trying to do. For example, you can use new threads that continue the work that was performed on the thread that completed the execution. You can also learn the java.util.concurrent package .

0
source share

Perhaps there is a better way to do this if you want the thread to stop and restart several times. I have tile caching in C ++ that does something like this; it pauses when it ends, and does not pause when necessary again. I am new to Java, but from what I can tell, you can use Object.wait () to pause and Object.notify () to resume threads. Perhaps you can check them in the documentation and redesign your thread to pause and resume, not exit.

-1
source share

All Articles