簡體   English   中英

如何中斷執行程序線程

[英]How to interrupt executor thread

有什么正確的方法來中斷執行者的線程? 我有這個:名稱為Worker的線程類,帶有方法:

public void run() {
    while(!(Thread.currentThread().isInterrupted()){
        System.out.println("work " + Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted());
    }
}

和主類:

ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
Worker worker = new Worker();                   
executorService.execute(worker);  

我試圖打電話給worker.interrupt(); executorService.shutdownNow(); 但是我的線程繼續運行,並且isInterrupted()為false。

您可以張貼所有相關代碼嗎? 根據您提供的信息,我無法重現您描述的行為。 參見下面的SSCCE ,它可以按預期工作-輸出:

工作池1線程1:false
工作池1線程1:false
工作池1線程1:false
....
線程已被中斷

碼:

public class Test {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        Worker worker = new Worker();
        executorService.execute(worker);
        executorService.shutdownNow();
    }

    public static class Worker extends Thread {

        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("work " + Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted());
            }
            System.out.println("Thread has been interrupted");
        }
    }
}

暫無
暫無

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

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