如果我有一个ExecutorService,我可以为其提供Runnable任务,我可以选择一个并中断吗?
我知道我可以取消返回的Future(也提到
Here: how-to-interrupt-executors-thread),但是如何引发InterruptedException.取消似乎没有这样做(事件虽然它应该通过查看源,可能OSX实现不同).至少这个片段不打印’它!’也许我误解了一些东西而不是自定义runnable获得异常?
public class ITTest {
static class Sth {
public void useless() throws InterruptedException {
Thread.sleep(3000);
}
}
static class Runner implements Runnable {
Sth f;
public Runner(Sth f) {
super();
this.f = f;
}
@Override
public void run() {
try {
f.useless();
} catch (InterruptedException e) {
System.out.println("it!");
}
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService es = Executors.newCachedThreadPool();
Sth f = new Sth();
Future> lo = es.submit(new Runner(f));
lo.cancel(true);
es.shutdown();
}
}