eldar
eldar

Reputation: 195

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.

Upvotes: 2

Views: 738

Answers (4)

assylias
assylias

Reputation: 328855

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.

Upvotes: 4

gd1
gd1

Reputation: 11403

You have to make the run() method of the thread terminate for some reason. How you achieve this depends on what the thread does.

  • If the thread is looping, you can stop it by raising a flag (checked by the condition of the loop).
  • If the thread is waiting over a Socket or any other stream, just close the stream.
  • If the thread is blocked on a call that can throw an InterruptedException, you can interrupt() the thread and ignore the exception.
  • If the thread is consuming the elements of a blocking queue, use the poison pill method, which means putting on the queue an element that just means "stop looping".

Upvotes: 1

Denis Rosca
Denis Rosca

Reputation: 3469

You could have isStopped()flag in your code. And the running thread should regularly check this flag to see if it should stop. Note that stopping a thread gracefully requires the running code to be written in a way that allows stopping.

You can take a look at this question for some more detailed answers

Upvotes: 1

Dan D.
Dan D.

Reputation: 32391

If you have a loop inside your run() method of your Thread then one option would be that your loop checks for the value of a flag on every iteration.

You can set the flag from outside the code, such as your thread would stop executing before starting the next iteration.

Upvotes: 0

Related Questions