问题
I think killing a thread
at precisely the time you want is a problem for many people. I recently ran across a way to kill a thread
by throwing an exception
. What are your thoughts/inputs on this? Has anyone implemented something like this before?
回答1:
The best way to stop a thread is to throw a InterruptedException
from within the thread. If an exception is thrown this makes sure that catch
and finally
blocks are executed, so the thread is able to release locks and resources, close files and connections it has opened, etc.
Often you want to stop a thread from another thread. You should not use the Thread.stop()
method, because it stops the thread immediately, resulting in deadlocks when the closed thread still own locks, files which are never closed, etc. The "official" way to stop a thread is to call the interrupt()
method on the thread you want to stop. This sets an internal flag, which can be checked by Thread.interrupted()
. Each thread should now poll Thread.interrupted()
at convenient times and throw an InterruptedException
if the flag is set:
if (Thread.interrupted()) throw new InterruptedException();
回答2:
You should not kill a thread. You should make it stop. If you have a loop, you should stop this loop. If you have some time consuming function, like network connect, you should stop this network function instead of killing thread. There is no guarantee to stop a thread with Thread.stop()
function
来源:https://stackoverflow.com/questions/27266249/killing-a-java-thread-by-throwing-exception