Java多執行緒15 Future設計模式
摘要:
Java多執行緒目錄
Future-> 代表的是未來的一個憑據
public interface Future<T> {
T get() throws InterruptedException;
}
AsynFu...
Future-> 代表的是未來的一個憑據
public interface Future<T> { T get() throws InterruptedException; }
AsynFuture -> Future具體實現類
public class AsynFuture<T> implements Future<T> { private volatile boolean done = false; private T result; public void done(T result){ synchronized (this){ this.result = result; this.done = true; this.notifyAll(); } } /** * 輪詢 沒有完成等待 */ @Override public T get() throws InterruptedException { synchronized (this) { while (!done) { this.wait(); } } return result; } }
FutureService -> 橋接Future和FutureTask
public class FutureService { /** * 需程序等待 */ public <T> Future<T> submit(final FutureTask<T> task) { AsynFuture<T> asynFuture = new AsynFuture<>(); new Thread(() -> { T result = task.call(); asynFuture.done(result); }).start(); return asynFuture; } /** * 執行完 自動回撥 * 無需程序等待 */ public <T> Future<T> submit(final FutureTask<T> task, final Consumer<T> consumer) { AsynFuture<T> asynFuture = new AsynFuture<>(); new Thread(() -> { T result = task.call(); asynFuture.done(result); consumer.accept(result); }).start(); return asynFuture; } }
FutureTask-> 將你的呼叫邏輯進行了隔離
public interface FutureTask<T> { T call(); }
需要時回撥
/** * Future-> 代表的是未來的一個憑據 * FutureTask-> 將你的呼叫邏輯進行了隔離 * FutureService -> 橋接Future和FutureTask */ public class SyncInvoker { public static void main(String[] args) throws InterruptedException { FutureService futureService = new FutureService(); Future<String> future = futureService.submit(() -> { try { Thread.sleep(10001); } catch (InterruptedException e) { e.printStackTrace(); } return "FINISH"; }); System.out.println("=============="); System.out.println("do other thing."); Thread.sleep(1000); System.out.println("=============="); /** * 呼叫也形成了阻塞 */ System.out.println(future.get()); } }
執行
============== do other thing. ============== FINISH
執行完自動回撥
//** * Future-> 代表的是未來的一個憑據 * FutureTask-> 將你的呼叫邏輯進行了隔離 * FutureService -> 橋接Future和FutureTask */ public class SyncInvoker { public static void main(String[] args) throws InterruptedException { FutureService futureService = new FutureService(); futureService.submit(() -> { try { Thread.sleep(10001); } catch (InterruptedException e) { e.printStackTrace(); } return "FINISH"; },System.out::println); System.out.println("=============="); System.out.println("do other thing."); Thread.sleep(1000); System.out.println("=============="); } }