簡體   English   中英

Executor 服務 shutdownNow ,它是如何工作的

[英]Executor service shutdownNow , how it works

根據方法shutdownNow (ExecutorService) 的文檔

There are no guarantees beyond best-effort attempts to stop
      processing actively executing tasks.  For example, typical
      implementations will cancel via {@link Thread#interrupt}, so any
      task that fails to respond to interrupts may never terminate

我有以下代碼:

public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newSingleThreadExecutor(r -> {
            final Thread thread = new Thread(r);
            thread.setDaemon(false);
            return thread;
        });
        service.submit(() -> {
            while (true) {
                Thread.sleep(1000);
                System.out.println("Done: " + Thread.currentThread().isInterrupted());
            }
        });
        Thread.sleep(3000);
        service.shutdownNow();
    }

這是輸出:

Done: false
Done: false

兩個循環后停止執行。 shutdownNow 如何中斷我的工作,我只有無限循環,沒有檢查Thread.currentThread.isInterrupted();

在我看來, shutdownNow只調用工作線程的中斷方法

Thread.sleep()檢查.isInterrupted()並在它被中斷時拋出一個InterruptedException 您的 lambda 隱式throws InterruptedException ,因此當執行程序關閉時它永遠不會到達您的System.out.println 您可以瀏覽ThreadPoolExecutor源代碼以了解這是如何發生的。

這是內部機制,但是如果你像下面一樣添加 try nad catch ,你將從 sleep 方法拋出 InterruptedException (因為線程已經被關閉方法中斷)所以關閉方法確實改變了線程狀態。

 public static void main(String[] args) throws InterruptedException {
    ExecutorService service = Executors.newSingleThreadExecutor(r -> {
        final Thread thread = new Thread(r);
        thread.setDaemon(false);
        return thread;
    });

    service.submit(() -> {
        try {
            while (true) {
                Thread.sleep(1000);
                System.out.println("Done: " + Thread.currentThread().isInterrupted());
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    });
    Thread.sleep(3000);
    service.shutdownNow();
}

暫無
暫無

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

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