本例演示主線程控制子線程的完整生命週期:啟動 → 中斷 → 掛起 → 恢復 → 停止。注意: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(),唯一安全停止方式 |
Thread.suspend():易死鎖(持有鎖時被掛起,其他線程嘗試獲取同鎖會永久阻塞)Thread.resume():配合 suspend 使用,同樣棄用Thread.stop():強制釋放所有鎖,導致數據不一致、對象損壞interrupt() + 協作式標誌 + wait/notify 或 Lock/Conditionclass 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; }
}
}
}
}
}
虛擬線程 (Thread.ofVirtual()) 輕量級、由 JVM 調度,傳統線程控制手段大多不再適用,推薦使用結構化併發 StructuredTaskScope 管理子任務生命週期。