應用場景:線程A需要線程B的執行結果,但沒必要一直等待線程B執行完,這個時候可以先拿到未來的Future對象,等線程B執行完再來取真實結果。
定義RealData真實數據類,其構造函數很慢,是用戶最后需要使用的數據,
static class RealData<T> {
protected T result;
public RealData(T result) {
this.result = result;
}
public T getResult() {
return result;
}
}
定義Future對象任務類,其是Future模式的關鍵,是真實數據RealData的代理,封裝了獲取RealData的等待過程。
public class FutureData<T> {
private static final UtilsLog lg = UtilsLog.getLogger(FutureData.class);
protected boolean isReady = false;
private RealData<T> realData = null;
private Object mutix = new Object();
public static FutureData request(final String request) {
lg.e("新建FutureData對象");
final FutureData future = new FutureData();
new Thread(new Runnable() {
@Override
public void run() {
UtilsThread.sleepIgnoreInteruptedException(5000);
lg.e("*************模擬耗時線程with time :5000******");
RealData realData = new RealData(request);
future.setRealData(realData);
}
}).start();
lg.e("返回新建的FutureData對象");
return future;
}
public T getResult() {
synchronized (mutix) {
while (!isReady) {
lg.e("getResult:before wait");
try {
mutix.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
lg.e("getResult:after wait");
}
lg.e("getResult:" + realData.getResult().toString());
return realData.getResult();
}
}
public void setRealData(RealData<T> realData) {
lg.e("執行設置數據:setRealData");
if (this.isReady) {
return;
}
this.realData = realData;
this.isReady = true;
synchronized (mutix) {
mutix.notify();
}
}
}
在業務層發起請求,並調用getResult方法等待返回任務執行結果。
FutureData futureData = FutureData.request("我要執行耗時任務");
lg.e("bootUpTestFunction result:" + futureData.getResult());
運行結果如下所示,分析知getResult方法中若isReady=false則調用wait()鎖定當前線程,直至setRealData中調用notify()后繼續執行wait后的方法。

關於Object的wait以及notify的相關知識點,請查看
Java之Object的wait與notify的方法解析