簡體   English   中英

Future.cancel(false)為執行中的任務返回true

[英]Future.cancel(false) returning true for task in execution

在我看來,Future.cancel(false)只有在實際上可以阻止任務執行時才返回true。

但是從下面的代碼我們可以看出它是矛盾的。

由於任務是癌症,它不應該打印"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);
    }
}

不幸的是,這個程序的輸出是“不期待這個聲明!!!”

有人可以解釋這種行為。

因為你調用canceled[0] = future.cancel(false); 參數為false 來自Future.cancel javadoc:

如果任務已經啟動,則mayInterruptIfRunning參數確定執行此任務的線程是否應該在嘗試停止任務時被中斷。

@param mayInterruptIfRunning {@code true}如果執行此任務的線程應該被中斷; 否則,允許完成正在進行的任務

當你調用cancel ,你的任務已經開始並允許它完成,所以取消操作實際上是成功的,如果你調用canceled[0] = future.cancel(true); ,則返回true canceled[0] = future.cancel(true); ,你不會看到輸出。

在您的代碼中, boolean[] canceled在兩個線程之間共享,並且沒有對此變量的同步訪問。 所以,結果會出乎意料。 另外,從https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html#cancel(boolean)的文檔中,如果無法取消任務,它將返回false,通常是因為它已經正常完成。 嘗試在取消任務后添加日志,以查看哪一個首先被執行(盡管它可能總是沒有幫助)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM