Search code examples
javamultithreadingshutdown

Shut down a single thread running


Suppose during my running I would like to shutdown a single thread gracefully!

I don't want to use Thread.stop() nor Thread.destroy() due to their unsafe behavior.

Note: I'm familiar with using ExecutorService.shutdown() option. But I would like to know the other way to implement.


Solution

  • The standard way to stop a thread is to call thread.interrupt();. To make it work, you need to make sure you thread responds to interruption, for example:

    Thread t = new Thread(new Runnable() { public void run {
        while(!Thread.currentThread().isInterrupted()) {
            //your code here
        }
    }});
    t.start();
    t.interrupt();
    

    This only works if the condition is checked regularly. Note that you can delegate the interruption mechanism to interruptible methods (typically I/O, blocking queues, sleep/wait provide methods that can block until they are interrupted).

    Note: In this example, you can also use:

        while(!interrupted()) {
            //your code here
        }
    

    interrupted() does the same thing as Thread.currentThread().isInterrupted() except that the interrupted flag is reset. Since it is your thread, it does not matter.