我需要终止一个未在我的代码中创建的线程。也就是说,线程对象是由api(Eclipse JFace)创建的。这是我的代码
ProgressMonitorDialog dialog = new ProgressMonitorDialog(null);
try {
IRunnableWithProgress rp = new IRunnableWithProgress(){
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
Thread.sleep(3000);
Thread t = Thread.currentThread();
t.getThreadGroup().list();
t.interrupt();
}
};
dialog.run(true, true, rp);
}
catch (Exception e) {
e.printStackTrace();
}
Thread.currentThread() 返回一个名为“ModalContext”的线程。 t.getThreadGroup().list() 行返回以下数据:
...
Thread[qtp1821431-38,5,main]
Thread[qtp1821431-39,5,main]
Thread[qtp1821431-40,5,main]
Thread[qtp1821431-42 Acceptor0 SelectChannelConnector@0.0.0.0:18080,5,main]
Thread[DestroyJavaVM,5,main]
Thread[ModalContext,5,main]
变量“dialog”和“rp”没有引用它们的可运行对象。而且他们没有任何关闭或取消的方法。所以我想直接杀死那个线程“ModalContext”。调用 t.interrupt() 不起作用。线程 MoadlContext 继续运行。我怎样才能杀死线程?谢谢
最佳答案
interrupt
method不会杀死线程。它在 Thread
上设置“中断”状态,如果它正在 hibernate 或等待 I/O,则它调用的方法将抛出 InterruptedException
。
但是,您在 sleep
完成后在当前线程上调用了 interrupt
,因此这只会设置“中断”状态。
您可以执行以下操作之一:
- 让另一个
Thread
在该Thread
上调用interrupt
。在run()
中,如果捕获到InterruptedException
或interrupted()
,则让方法完成返回true
。 - 声明一个
volatile boolean
变量(例如,isRunning
),在创建的线程中初始化为true
。如果它为false
,该线程将让run()
方法完成。在适当的时候让另一个Thread
将其设置为false
。
关于java线程: Thread.中断()不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32486717/