WebService 調用、遠程 RPC、複雜運算等長耗時操作若同步阻塞主線程,會導致 UI 凍結、回應停滯。本文示範「回調 + 線程」異步模式:主線程發起請求即返回,耗時任務背景執行完成後回調通知結果。
printNewCount() 顯示結果Viewer.printNewCount()public class Viewer {
private int count;
public Viewer(int count) { this.count = count; }
public void printNewCount(int newCount) {
System.out.println("New Count=" + newCount);
}
public int getCount() { return count; }
public void setCount(int count) { this.count = count; }
}
package com.sitinspring;
public class LongTimeResponse implements Runnable {
private Viewer viewer;
private int count;
public LongTimeResponse(Viewer viewer) {
this.viewer = viewer;
this.count = viewer.getCount();
caculateNewCount(); // 啟動異步計算
}
private void caculateNewCount() {
Thread thread = new Thread(this);
thread.start(); // 背景線程執行 run()
}
public void run() {
try { Thread.sleep(10000); } // 模擬 10 秒耗時操作
catch (Exception ex) { ex.printStackTrace(); }
viewer.printNewCount(count * count * count); // 回調通知結果
}
}
Viewer viewer = new Viewer(10);
LongTimeResponse ltr = new LongTimeResponse(viewer);
viewer.printNewCount(123); // 主線程立即執行
輸出順序:
New Count=123 // 立即輸出,主線程未阻塞 ... 10 秒後 ... New Count=1000 // 背景線程完成,回調輸出
LongTimeResponse 持有 Viewer 引用,完成時主動通知run(),由獨立線程執行Future/CompletableFuture (JDK 1.5+/1.8) 統一異步結果處理ExecutorService 管理線程池,避免頻繁建立銷毀Future.get(timeout, TimeUnit) 防止無限等待SwingUtilities.invokeLater() 等轉派「回調 + 線程」是處理耗時操作的經典模式,核心在於主流程不等待、結果主動通知。現代開發建議配合 CompletableFuture、RxJava、Kotlin Coroutines 等高階異步框架,進一步簡化錯綜複雜的回調鏈。