Reputation: 195
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
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
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.
Socket
or any other stream, just close the stream.InterruptedException
, you can interrupt()
the thread and ignore the exception.Upvotes: 1
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
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