JDK **不提供** Thread.addTerminationListener() 等內置 API。線程結束後僅釋放資源,無事件回調。
Thread t = new Thread(() -> { /* work */ });
t.start();
t.join(); // 當前線程阻塞,直到 t 結束
System.out.println("Thread finished");
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");
CompletableFuture f1 = CompletableFuture.runAsync(() -> work());
CompletableFuture f2 = CompletableFuture.runAsync(() -> work());
CompletableFuture.allOf(f1, f2).join(); // 等待所有完成
// 或 thenRun/thenAccept 鏈式回調
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。