我有几个实现 Runnable 的对象接口(interface),我在单独的 Threads 中执行它们。本质上,在 Runnable 对象的 run() 方法中,我执行了一些网络 Activity ,其中包括调用在等待输入(来自网络)时阻塞的方法。请注意,我没有任何故意的暂停,即 Thread.sleep() 调用。任何暂停都是由调用可能阻塞的方法引起的。
这些 Runnable 对象受 GUI 的控制,因此 GUI 界面和我希望向用户提供的一个功能是能够结束执行我的 Runnable 对象的线程,但是我无法理解该怎么做这个。
一种明显的方法是调用 Runnable 对象 Thread 的 Thread.interrupt() 方法,但是对 Thread 方法的调用如何传播到 Runnable 对象呢?例如,我无法使用 try-catch,在 Runnable 对象中捕获 InterruptedException 似乎是不允许的;我的 IDE (netbeans) 提示 InterruptedException
永远不会在 run()
方法中抛出。
我的代码如下,为简洁起见,进行了删除。 以下行在 GUI 线程中的 GUI 代码中执行:
digiSearch = new DigiSearch(hostIP,this);
digiSearchThread = new Thread(digiSearch);
digiSearchThread.start();
以下是我的 Runnable 类,我希望/需要捕获其执行线程的中断。
public class DigiSearch implements Runnable {
private String networkAdapterIP;
private DigiList digiList;
public DigiSearch (String ipAddress, DigiList digiList){
networkAdapterIP = ipAddress;
this.digiList = digiList;
}
@Override
public void run() {
try{
/*
* Do some network and other activities here which includes calling some blocking methods. However I would like to interrupt the run() method if possible by calling Thread.interrupt()
*/
} catch (Exception ex){
digiList.digiListException(ex);
} catch (Throwable t){
System.out.println("Search thread interrupted");
}
}
}
有人可以启发我如何实现这一目标,或者解决我对中断线程的误解吗?
最佳答案
您是否有任何抛出IOException
的阻塞方法?如果是这样,这可能是您的 InterruptedException
占位符。其中许多方法是在引入 InterruptedException
之前编写的,因此它们不会更新会破坏旧代码的接口(interface),而是将 InterruptedException
包装在 IOException
中>.
如果情况并非如此,那么您就有点陷入困境了。例如,如果您编写一个 Runnable 来创建一个只工作且从不 hibernate 的无限循环,则中断该线程不会导致 InterruptedException。 Runnable
负责定期检查 Thread.interrupted()
。
关于java - 如何中断线程并捕获 Runnable 对象中的中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13475153/