I am trying to close all my thread in my threadpool.
Usually I try:
while(!Thread.currentThread().isInterrupted()) {...
To close the while loop...
But I have one Thread which only consists about
while(!Thread.currentThread().isInterrupted()) {//which is true
This is how I close the threads:
pool.shutdownNow();
So how would you close such a Thread?
Create a Queue from Queue import Queue and pass it to the thread func. Inside the while loop read from the queue (using get ). The main body of the code should put something in the queue that will flag the thread to stop.
Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.
You can add a volatile
boolean flag
.
public class Worker implements Runnable {
volatile boolean cancel = false;
@Override
public void run() {
while (!cancel) {
// Do Something here
}
}
public void cancel() {
cancel = true;
}
}
Now you can just call
worker.cancel();
Update:
From Java doc of shutdownNow()
Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
here are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.
So either you will have to define your interruption policy by preserving the interrupts
catch (InterruptedException ie) {
// Preserve interrupt status
Thread.currentThread().interrupt();
}
Instead of that you might use a self created flag as condition for the while loop.
public class MyClass implements Runnable
{
private volatile boolean running = true;
public void stopRunning()
{
running = false;
}
public void run()
{
while (running)
{
}
// shutdown stuff here
}
}
Now, to stop it, just call:
myClassObject.stopRunning();
This will let the code finish normally.
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