【发布时间】:2013-02-19 00:21:21
【问题描述】:
因此,此资源 (http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html) 建议在线程本身不处理中断时设置线程中的中断位,“以便调用堆栈上更高的代码可以了解中断如果它想回复它,就回复它。”
假设我正在使用 ExecutorService 在不同的线程中运行某些东西。我构造了一个 Callable 并将这个 Callable 传递给 ExecutorService.submit(),它返回一个 Future。如果 Callable 被中断然后重置中断位,则关联的 Future 在调用 Future.get() 时不会抛出 InterruptedException。那么如果这个 Future 是主线程访问生成的线程的唯一方式,那么在 Callable 中设置中断位的目的是什么。
class MyCallable implements Callable<String> {
@Override
public String call() {
while (!Thread.currentThread().isInterrupted()) {
}
Thread.currentThread().interrupt();
return "blah";
}
}
ExecutorService pool = makeService();
Future<String> future = pool.submit(new MyCallable());
// Callable gets interrupted and the Callable resets the interrupt bit.
future.get(); // Does not thrown an InterruptedException, so how will I ever know that the Callable was interrupted?
【问题讨论】:
标签: java interrupt future callable interrupted-exception