How can we suspend/pause thread based on its id? ... I have thread id I want to suspend and kill the thread.
The right way to kill a thread these days is to interrupt()
it. That sets the Thread.isInterrupted()
to true and causes wait()
, sleep()
, and a couple other methods to throw InterruptedException
.
Inside of your thread code, you should be doing something like the following which checks to make sure that it has not been interrupted.
// run our thread while we have not been interrupted
while (!Thread.currentThread().isInterrupted()) {
// do your thread processing code ...
}
Here's an example of how to handle interrupted exception inside of a thread:
try {
Thread.sleep(...);
} catch (InterruptedException e) {
// always good practice because throwing the exception clears the flag
Thread.currentThread().interrupt();
// most likely we should stop the thread if we are interrupted
return;
}
The right way to suspend a thread is a bit harder. You could set some sort of volatile boolean suspended
flag for the thread that it would pay attention to. You could also use object.wait()
to suspend a thread and then object.notify()
to start it running again.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…