Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 250
Shaitan00 Avatar asked Dec 10 '09 15:12

Shaitan00


People also ask

Can you restart a thread in Java?

Once a thread enters dead state it cannot be restarted.

Which method restarts the thread in Java?

start(); thread. join(); // wait for run to end // restart the runnable thread = new Thread(someRunnable); thread. start();

How do you stop a thread in Java?

Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected. A thread will also move to the dead state automatically when it reaches the end of its method.

How do you pause a thread?

Methods Used: sleep(time): This is a method used to sleep the thread for some milliseconds time. suspend(): This is a method used to suspend the thread. The thread will remain suspended and won't perform its tasks until it is resumed. resume(): This is a method used to resume the suspended thread.


1 Answers

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 
like image 53
Taylor Leese Avatar answered Oct 11 '22 13:10

Taylor Leese