Java:手動停止線程的幾種方式

記錄……

 

 

1、業務邏輯實現,藉助AtomicBoolean等相關api做標識符
2、stop()方法,但此方法過於粗暴,可能會導致安全問題
3、interrupt()方法,推薦

①、線程內部

@Override
public void run() {
    while (true){
        if(Thread.currentThread().isInterrupted()){
            log.info("退出當前線程:{}", Thread.currentThread().getName());
            break;
        }
        log.info("業務邏輯……");
    }
}

②、主線程或業務代碼中


Thread thread = new Thread();
if(!thread.isInterrupted()){
    try {
        thread.interrupt();
    }catch (Exception e){
        log.error("線程停止失敗:{},線程:{}", e.getMessage(), thread.getName());
    }
}

 

 

需要注意的是:
interrupt()並不會直接停止線程,而是告訴線程希望停止執行。
因此在線程內容執行體中,使用Thread.currentThread().isInterrupted()判斷interrupt並做出相應處理

即interrupt()和Thread.currentThread().isInterrupted()組合使用

 

相關文檔:https://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章