future接口的cancel方法無法正常取消執行中的線程


future的cancel方法取消任務時會給線程發一個中斷信號,但是線程並沒有真正停止,需要線程根據中斷信號自己決定線程中斷的時機,實例如下:

/**
* "!Thread.currentThread().isInterrupted()"不能省略,否則本線程無法被future#cancel方法停止!!
*/
while ((sendCount--) > 0 && !Thread.currentThread().isInterrupted()) {
    // 業務邏輯
}

補充:

java真正中斷線程的方法只有早期的stop方法,但是因為容易破壞代碼塊並且容易產生死鎖,已經不推薦使用。推薦使用"兩階段終止模式"處理線程中斷:

class TestInterrupt {
    private Thread thread;
    public void start() {
        thread = new Thread(() -> {
            while(true) {
                Thread current = Thread.currentThread();
                if(current.isInterrupted()) {
                    // 做完善后工作后終止線程
                    log.debug("善后工作");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    log.debug("業務邏輯");
                } catch (InterruptedException e) {
                	current.interrupt();
                }
            }
        });
        thread.start();
    }
    public void stop() {
        thread.interrupt();
    }
}

參考:

https://www.jianshu.com/p/9fc446c2c1be


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM