Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a thread which has a while(true)?

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?

like image 321
maximus Avatar asked Oct 29 '12 10:10

maximus


People also ask

How do you stop a while loop in 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.

How do you kill a thread?

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.


2 Answers

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();
   }
like image 62
Amit Deshpande Avatar answered Oct 12 '22 23:10

Amit Deshpande


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.

like image 28
Martijn Courteaux Avatar answered Oct 13 '22 01:10

Martijn Courteaux