在我看來,如果實際上有可能阻止任務的執行,那麼Future.cancel(false)應該只返回true。Future.cancel(false)在執行任務中返回true
但是從下面的代碼我們可以看出它是矛盾的。
由於任務canceld它不應該打印"Not expecting this statement!!!"
public class Test {
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
final boolean[] canceled = { false };
ScheduledFuture<?> future = executor.schedule(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
if (canceled[0])
System.out.println("Not expecting this statement!!!");
} catch (InterruptedException e) {
}
}
}, 0, TimeUnit.SECONDS);
Thread.sleep(100);
canceled[0] = future.cancel(false);
executor.shutdown();
executor.awaitTermination(2, TimeUnit.SECONDS);
}
}
不幸的是這個程序的輸出爲「不奢望這個說法!」
有人可以解釋這種行爲。
在我的情況下,它返回true.Hence問題提出 –
嘗試增加主要方法中的睡眠時間。您可能會看到不同的答案 – prasanth
誰給這個問題+1這麼快,它在前15秒內得到+1。 –