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

java, multithreading, thread-safety, threadpool

Solution

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();
   }

Problem

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?

Original source