在我的应用程序中,每个请求都有自己的线程。我使用 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();
}
}
}