Shaitan00 Shaitan00 - 4 months ago 55
Java Question

How to start/stop/restart a thread in Java?

I am having a real hard time finding a way to start, stop, and restart a thread in Java.

Specifically, I have a class

Task
(currently implements
Runnable
) in a file
Task.java
. My main application needs to be able to START this task on a thread, STOP (kill) the thread when it needs to, and sometimes KILL & RESTART the thread...

My first attempt was with
ExecutorService
but I can't seem to find a way for it restart a task. When I use
.shutdownnow()
any future call to
.execute()
fails because the
ExecutorService
is "shutdown"...

So, how could I accomplish this?

Answer

Once a thread stops you cannot restart it. However, there is nothing stopping you from creating and starting a new thread.

Option 1: Create a new thread rather than trying to restart.

Option 2: Instead of letting the thread stop, have it wait and then when it receives notification you can allow it to do work again. This way the thread never stops and will never need to be restarted.

Edit based on comment:

To "kill" the thread you can do something like the following.

yourThread.setIsTerminating(true); // tell the thread to stop
yourThread.join(); // wait for the thread to stop
Comments