标签:
static class RealData<T> {
protected T result;
public RealData(T result) {
this.result = result;
}
public T getResult() {
return result;
}
}
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();
}
}
}
FutureData futureData = FutureData.request("我要执行耗时任务");
lg.e("bootUpTestFunction result:" + futureData.getResult());
标签:
原文地址:http://www.cnblogs.com/linux007/p/5782704.html