Java并发,实际上,国家在以下几点:理解中断取消与未来
线程只能由其所有者中断;车主可以 封装在一个 适当的取消机制线程的中断政策的知识,如关机方法现在
让我们来看看标准FutureTask
实现:
public boolean cancel(boolean mayInterruptIfRunning){
//...
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
t.interrupt(); //Future task may not be an owner,
//yet it interrupts the running thread.
}
//...
}
//...
}
那么,为什么它安全?在ThreadPoolExecutor
情况下,这newTaskFor
的实现只是
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
它是安全的调用是这样的:
ExecutorService es;
Callable<Integer> task;
//init es, task
Future<Integer> ft = es.submit(task);
ft.cancel(true); //Attention at this line, thread may be interrupted
在ThreadPoolExecutor
情况下,我们不知道有关线程中断的政策,无论是FutureTask
。不过,我们通过FutureTask
来打断它。这是一种令人困惑的...
但中断是专门为取消活动而设计的机制。对于'ExecutorService',我们最好不要对它的线程中断策略做任何假设,我想......但是如果我们在由'ExecutorService'生成的'Future'上调用'cancel(true)',我们实际上会所以。否则,一项任务(即使是可重复中断的任务)也不会被“中断”并被允许完成。这种“取消”似乎对我来说完全没有意义。 – user3663882
我咨询了ThreadPoolExecutor :: shutdownNow()的来源。很明显,它会中断所有工作线程。 – user3663882