Futurefuture = executor.submit(task); future.get(); // 阻塞等待,無法感知完成時刻 // 或輪詢 while (!future.isDone()) { Thread.sleep(100); } // 低效、延遲
缺陷:無回調通知機制,只能主動輪詢或阻塞等待。
核心能力:
public interface IFutureextends Future { boolean isSuccess(); // 是否成功完成 V getNow(); // 立即獲取結果(未完成返回 null) Throwable cause(); // 失敗原因 boolean isCancellable(); // 是否可取消 // 等待完成 IFuture await() throws InterruptedException; boolean await(long timeout, TimeUnit unit) throws InterruptedException; IFuture awaitUninterruptibly(); boolean awaitUninterruptibly(long timeout, TimeUnit unit); // 監聽器 IFuture addListener(IFutureListener listener); IFuture removeListener(IFutureListener listener); } public interface IFutureListener { void operationCompleted(IFuture future) throws Exception; }
// 三種終態對象
private static final Object SUCCESS_SIGNAL = new Object(); // 正常完成,結果為 null
private static final class CauseHolder { final Throwable cause; ... } // 異常完成
// 正常完成有結果:直接存結果對象
volatile Object result; // null=未完成,非空=已完成
CopyOnWriteArrayList> listeners = new CopyOnWriteArrayList<>();
protected boolean setSuccess0(Object result) {
synchronized (this) {
if (this.result != null) return false; // 已完成
this.result = (result == null) ? SUCCESS_SIGNAL : result;
notifyAll(); // 喚醒所有 await 線程
}
notifyListeners(); // 異步回調監聽器
return true;
}
protected boolean setFailure0(Throwable cause) {
synchronized (this) {
if (this.result != null) return false;
this.result = new CauseHolder(cause);
notifyAll();
}
notifyListeners();
return true;
}
private void notifyListeners() {
for (IFutureListener l : listeners) {
try { l.operationCompleted(this); } catch (Exception e) { e.printStackTrace(); }
}
}
public IFutureawait() throws InterruptedException { if (isDone()) return this; synchronized (this) { while (!isDone()) { wait(); // 釋放鎖,進入 WAITING } } return this; } public boolean await(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); long deadline = System.nanoTime() + nanos; synchronized (this) { while (!isDone()) { if (nanos <= 0) return false; wait(nanos / 1_000_000, (int)(nanos % 1_000_000)); nanos = deadline - System.nanoTime(); } return true; } }
public class DelayAdder {
public IFuture add(long delayMs, int a, int b) {
DelayAdditionFuture future = new DelayAdditionFuture();
new Thread(new DelayTask(delayMs, a, b, future)).start();
return future;
}
private static class DelayTask implements Runnable {
private final long delay; private final int a, b; private final DelayAdditionFuture future;
public void run() {
try {
Thread.sleep(delay);
future.setSuccess(a + b); // 正常完成
} catch (InterruptedException e) {
future.setFailure(e); // 異常完成
}
}
}
}
// 客戶端調用:註冊監聽器,無需輪詢
adder.add(3000, 1, 2).addListener(future -> {
System.out.println("結果: " + future.getNow()); // 3秒後自動打印 3
});
CompletableFuture,功能更強、API 更豐富