首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 線程結束通知機制:無內置監聽器,需自定義協調方案

     編輯:程式設計綜合問答

現狀

JDK **不提供** Thread.addTerminationListener() 等內置 API。線程結束後僅釋放資源,無事件回調。

四種協調方案

1. Thread.join() (阻塞等待)

Thread t = new Thread(() -> { /* work */ });
t.start();
t.join(); // 當前線程阻塞,直到 t 結束
System.out.println("Thread finished");

2. CountDownLatch / CyclicBarrier (一對多/多對多)

CountDownLatch latch = new CountDownLatch(3);
for (int i=0;i<3;i++) new Thread(()->{ try{work();} finally{latch.countDown();} }).start();
latch.await(); // 主線程等待 3 個子線程全部結束
System.out.println("All done");

3. CompletableFuture (現代異步編排)

CompletableFuture f1 = CompletableFuture.runAsync(() -> work());
CompletableFuture f2 = CompletableFuture.runAsync(() -> work());
CompletableFuture.allOf(f1, f2).join(); // 等待所有完成
// 或 thenRun/thenAccept 鏈式回調

4. 共享標誌位 (簡單輪詢/通知)

volatile boolean finished = false;
Thread t = new Thread(() -> { try{work();} finally{finished = true;} });
t.start();
// 監聽端
while (!finished) { Thread.sleep(100); } // 或用 LockSupport.parkNanos
System.out.println("Detected finish");

選擇建議

  • 單線程等待 → join()。
  • 多線程聚合 → CountDownLatch / CompletableFuture。
  • 異步流水線 → CompletableFuture 鏈式 API。
  • 避免忙輪詢,必要時用 LockSupport.park 釋放 CPU。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved