Shaitan00 Shaitan00 - 1 year ago 229
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

(currently implements
) in a file
. 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
but I can't seem to find a way for it restart a task. When I use
any future call to
fails because the
is "shutdown"...

So, how could I accomplish this?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download