我通过实现可运行接口创建了类,然后在项目的其他类中创建了许多线程(近 10 个)。
如何停止其中一些线程?
The simplest方法是interrupt()
它,这会导致Thread.currentThread().isInterrupted()
回来true
,也可能会抛出一个InterruptedException
在某些情况下线程是waiting, 例如Thread.sleep()
, otherThread.join()
, object.wait()
etc.
在 - 的里面run()
您需要捕获该异常和/或定期检查的方法Thread.currentThread().isInterrupted()
重视并做某事(例如,突破)。
注:虽然Thread.interrupted()
看起来一样isInterrupted()
,它有一个令人讨厌的副作用:调用interrupted()
clears the interrupted
标志,同时调用isInterrupted()
才不是。
其他非中断方法涉及使用“停止”(volatile
) 正在运行的线程监视的标志。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)