这些天杀死线程的正确方法就是使用
interrupt()它。这集
Thread.isInterrupted()真和原因
wait(),
sleep()以及一些其他的方法来扔
InterruptedException。
在线程代码内部,您应该执行类似以下的操作,检查以确保它没有被中断。
// run our thread while we have not been interrupted while (!Thread.currentThread().isInterrupted()) { // do your thread processing pre ... }这是一个如何在线程内部处理中断异常的示例:
try { Thread.sleep(...); } catch (InterruptedException e) { // always good practice because catching the exception clears the flag Thread.currentThread().interrupt(); // most likely we should stop the thread if we are interrupted return; }挂起线程的正确方法要困难一些。您可以
volatile booleansuspended为它要注意的线程设置某种标志。然后
wait(),您可以使用和
notify()重新启动线程。



