多線程實現線程中斷(一)

在業務需求中會有大文件或者限制時間返回,規定時間沒返回則認爲失敗,關閉線程
創建一個ThreadClose類

public class ThreadClose {
 // 創建線程保證兩個方法調用同一個線程
    private Thread thread ;
    private Boolean flage = false;
    
    public void execute(Runnable task) {
        thread = new Thread(){
            @Override
            public void run() {
                Thread runner = new Thread(task);
                runner.start();
                // 開啓線程守護
                runner.setDaemon(true);
                try {
                // 等待線程執行完畢
                    runner.join();
                    flage = true;
                } catch (InterruptedException e) {
                    //e.printStackTrace();
                }
            }
        };
        thread.start();
}
    public void shutdown(Long milles){

        Long currentTime = System.currentTimeMillis();
        while (!flage){

            if(System.currentTimeMillis() - currentTime >= milles){
                //任務超時需要結束中斷
                System.out.println("任務超時需要中斷");
                // 中斷線程
                thread.interrupt();
                break;
            }}
        flage = false;
    }
}

模擬大文件傳輸
創建ThreadBreak

  public static void main(String[] args) throws InterruptedException {
          ThreadClose  threadClose = new ThreadClose();
          Long start = System.currentTimeMillis();
          threadClose.execute(() -> {
              // 模擬大文件傳輸
             while (true){

             }
          });
          threadClose.shutdown((long) 1000);
            Long endTime = System.currentTimeMillis();
            System.out.println(start - endTime);
        }

這樣在你設定的1000毫秒內如果threadClose方法沒有執行完畢會讓這個線程優雅停止。
如果你這個任務執行只有500毫秒

  public static void main(String[] args) throws InterruptedException {
          ThreadClose  threadClose = new ThreadClose();
          Long start = System.currentTimeMillis();
          threadClose.execute(() -> {
              // 模擬大文件傳輸
              try {
                  Thread.sleep(500);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          });
          threadClose.shutdown((long) 1000);
            Long endTime = System.currentTimeMillis();
            System.out.println(start - endTime);
        }

運行結果557毫秒會自己停止。

用戶線程,不隨着其他人的死亡而死亡,只有兩種情況死掉,1在run中異常終止,而正常把run執行完畢。線程死亡

守護線程,隨着用戶線程的死亡而死亡,當用戶線程死完了守護線程也死了,比如gc垃圾回收線程。用戶線程存在,那gc就有活着的必要,反之間用了

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