我通过实现可运行接口(interface)创建了类,然后在我的项目的其他一些类中创建了许多线程(近 10 个)。
如何停止其中一些线程?
最佳答案
最简单的方式就是interrupt()
它,这会导致Thread.currentThread().isInterrupted()
返回true
,并且在线程正在等待的某些情况下也可能抛出InterruptedException
,例如Thread.sleep()
, otherThread.join()
, object.wait()
等
在 run()
方法中,您需要捕获该异常和/或定期检查 Thread.currentThread().isInterrupted()
值并执行某些操作(例如例如,爆发)。
注意:虽然 Thread.interrupted()
看起来和 isInterrupted()
一样,但它有一个讨厌的副作用:调用 interrupted()
清除 interrupted
标志,而调用isInterrupted()
不会。
其他非中断方法涉及使用正在运行的线程监控的“停止”(volatile
)标志。
关于java - 如何停止通过实现可运行接口(interface)创建的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10630737/