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();
}
}
參考:
