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