为什么在可调用中设置中断位 [英] Why set the interrupt bit in a Callable

查看:143
本文介绍了为什么在可调用中设置中断位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,这个资源( http://www.ibm .com / developerworks / java / library / j-jtp05236 / index.html )建议在Thread没有处理中断本身的情况下设置线程中的中断位,以便代码更高如果想要,可以在调用堆栈中了解中断并对其进行响应。

So, this resource (http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html) suggest to set the interrupt bit in a Thread when that Thread does not deal with the interrupt itself, "so that code higher up on the call stack can learn of the interruption and respond to it if it wants to."

假设我正在使用ExecutorService来运行某些内容一个不同的线程。我构造一个Callable并将此Callable传递给ExecutorService.submit(),它返回一个Future。如果Callable被中断然后重置中断位,则在调用Future.get()时,关联的Future不会抛出InterruptedException。那么在Callable中设置被中断位的目的是什么呢?如果这个Future是主线程可以访问生成的线程的唯一方法。

Let's say I'm using an ExecutorService to run something in a different Thread. I construct a Callable and pass this Callable into ExecutorService.submit(), which returns a Future. If the Callable gets interrupted and then resets the interrupt bit, the associated Future will not throw an InterruptedException when Future.get() is called. So what would be the purpose of setting the interrupted bit in the Callable if this Future is the only way the main Thread has access to the spawned Thread.

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?


推荐答案

你说错了,中断标志之间没有传递这种情况下的2个线程(这就是内置的ExecutorService是出于何种原因而设计的)。如果您希望主线程看到可调用的中断状态,则必须从您的调用方法中抛出InterruptedException。

You are correct that the interrupt flag is not passed between the 2 threads in this scenario (that's how the built in ExecutorService was designed for whatever reason). If you want the main thread to see the interrupted status of the callable, then you must throw InterruptedException from your call method.

class MyCallable implements Callable<String> {
  @Override
  public String call() {
    // ...
    if(Thread.currentThread().isInterrupted()) {
      throw new InterruptedException();
    }
    return "blah";
  }
}

注意,你仍然不会直接从中获取InterruptedException在这种情况下, Future.get()。因为它是由callable引发的,所以它将被包装在 ExecutionException 中(这样你就可以区分可调用的中断和主线程的中断)。

Note, you still won't get InterruptedException directly from Future.get() in this scenario. since it was thrown by the callable, it will be wrapped in an ExecutionException (this is so you can distinguish between an interruption of the callable and an interruption of the main thread).

这篇关于为什么在可调用中设置中断位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆