在我的应用程序中,每个请求都有自己的线程。我使用 JMX/JConsole 来监视它们,测量耗时。如果请求需要太多时间,我想通过中断底层线程来停止它。
在我从 JConsole 调用的方法中,我遍历线程列表并在正确的实例上调用 interrupt()。
然而,简单地在线程实例上调用 interrupt() 方法只会设置一个标志,所以我也需要抛出一个 InterruptedException。
但是这个 InterruptedException 将应用于 currentThread 而不是我实际想要停止的线程。任何提示如何关闭标记的线程?
while (iterator.hasNext()) {
RequestHolder rh = iterator.next();
if (rh.getThread().getId() == threadId) {
rh.getThread().interrupt();
if(rh.getThread().isInterrupted()){
throw new InterruptedException();
}
}
}
最佳答案
But this InterruptedException will apply to currentThread instead of the thread I actually want to stop.
您可以使用isInterrupted
检查任何线程的中断状态。但是,如果您不知道如何以及何时消耗中断,则不建议将其作为黑盒方法。
Any hint how to shut down the flagged thread?
您不能从另一个线程完全关闭一个线程。
但是很简单。在正在运行的线程中,定期检查 Interruption
,例如在循环中捕获 InterruptedException
以获取阻塞函数。当你看到线程中的中断时,让它自己终止。从某种意义上说,线程实现了自己的终止策略。
关于java - 如何关闭来自不同线程的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16523106/