首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

[JAVA100例] 第66例:線程控制——中斷、掛起、恢復與停止

     編輯:Java 相關知識

本例演示主線程控制子線程的完整生命週期:啟動 → 中斷 → 掛起 → 恢復 → 停止。注意:suspend()/resume()/stop() 已棄用(死鎖風險),示例採用 wait()/notify() 實現安全掛起恢復。

核心代碼

public class threadCtrl {
  public static void main(String[] main) { new threadCtrl(); }

  threadCtrl() {
    try {
      Thread tm = Thread.currentThread();
      threadchild td = new threadchild();
      td.start();
      tm.sleep(500);

      System.out.println("interrupt child thread");
      td.interrupt();  // 中斷睡眠

      System.out.println("let child thread wait!");
      tm.sleep(1000);

      System.out.println("let child thread working");
      td.fauxresume();  // 安全恢復
      tm.sleep(1000);

      td.runflag = false;  // 協作式停止
      System.out.println("main over..............");
    } catch (InterruptedException ie) { System.out.println("inter main::" + ie); }
    catch (Exception e) { System.out.println("main::" + e); }
  }
}

class threadchild extends Thread {
  boolean runflag = true;
  boolean suspended = true;

  public synchronized void fauxresume() {
    suspended = false;
    notify();  // 喚醒 wait()
  }

  public void run() {
    while (runflag) {
      System.out.println("I am working..............");
      try { sleep(1000); }
      catch (InterruptedException e) { System.out.println("sleep::" + e); }
      
      synchronized (this) {
        try {
          if (suspended) wait();  // 掛起點
        } catch (InterruptedException e) { System.out.println("wait::" + e); }
      }
    }
    System.out.println("thread over...........");
  }
}

關鍵機制解析

操作實現方式說明
中斷interrupt()打斷 sleep()/wait(),拋出 InterruptedException,需捕獲處理
掛起synchronized + wait()釋放鎖並進入等待集,必須在同步塊中調用
恢復synchronized + notify()喚醒等待線程,必須持有同一對象鎖
停止協作式標誌 runflag=false線程檢查標誌主動退出 run(),唯一安全停止方式

棄用 API 警示

  • Thread.suspend():易死鎖(持有鎖時被掛起,其他線程嘗試獲取同鎖會永久阻塞)
  • Thread.resume():配合 suspend 使用,同樣棄用
  • Thread.stop():強制釋放所有鎖,導致數據不一致、對象損壞
  • 現代替代:interrupt() + 協作式標誌 + wait/notify 或 Lock/Condition

最佳實踐模板

class SafeThread extends Thread {
  private volatile boolean running = true;
  private volatile boolean paused = false;
  private final Object pauseLock = new Object();

  public void requestPause() { paused = true; }
  public void requestResume() { 
    synchronized (pauseLock) { paused = false; pauseLock.notifyAll(); }
  }
  public void requestStop() { running = false; interrupt(); }

  public void run() {
    while (running) {
      // 1. 正常工作
      doWork();
      
      // 2. 暫停檢查點
      synchronized (pauseLock) {
        while (paused && running) {
          try { pauseLock.wait(); } catch (InterruptedException e) { return; }
        }
      }
    }
  }
}

JDK 21+ 虛擬線程時代

虛擬線程 (Thread.ofVirtual()) 輕量級、由 JVM 調度,傳統線程控制手段大多不再適用,推薦使用結構化併發 StructuredTaskScope 管理子任務生命週期。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved