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?
Once a thread enters dead state it cannot be restarted.
start(); thread. join(); // wait for run to end // restart the runnable thread = new Thread(someRunnable); thread. start();
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With