Stopping a running thread I am trying to stop an executing runnable instance after the run method has been called.

I have come up with the below approach

    public class StoppableWorkflowTask implements Runnable {
        volatile Thread runner = null;

        @Override
        public void run() {
            runner = Thread.currentThread();
            try {

                while (true) {
                    System.out.println("Stop Thread " + Thread.currentThread().getId());
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }

        void stop() {
            runner.stop();
        }

    }

public class StoppableWorkflowTaskTest {
    public static void main(String[] args) {
        StoppableWorkflowTask stoppableTask = new StoppableWorkflowTask();

        Thread thread = new Thread(stoppableTask);

        thread.start();
        System.out.println(thread.currentThread().getId());

        try {
            stoppableTask.stop();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}


As per Java documention it is unsafe to call thread.stop(). I have checked few examples , but all either use thread.sleep() which can be terminated on interrupt.
The recommended way from Oracle is Thread.interrupt().  For example:

public void stop() {
    Thread thread = runner;
    runner = null;
    thread.interrupt();
}

public void run() {
    runner = Thread.currentThread();
    while (runner != null) {
        System.out.println("Stop Thread " + Thread.currentThread().getId());
    }
    System.out.println(" Done ");
}


It is true that sleep() can be interrupted (which will raise an InterruptedException), which is what the interrupt() will do.  However, afterwards the Thread can continue doing whatever it wants after being “interrupted”, so you must also check for a stop-condition of some kind.  Above, we check runner != null.  But as you can see above, you don’t need a sleep() in the worker thread.

If you don’t want to run the Thread in a loop, or you have many different loops where the task may spin, you will have to make the stop check in each of those places.