设计模式与并发之Future模式
核心思想:异步调用。
/**
* @author: Tang Jiujia
* @version: 2017/9/18 0018 15:22
*/
public interface Data { String getResult();
}
/**
* @author: Tang Jiujia
* @version: 2017/9/18 0018 15:23
*/
public class RealData implements Data{ protected final String result; public RealData(String para){
StringBuffer bf=new StringBuffer();
for (int i=0;i<10;i++){
bf.append(para);
try{
Thread.sleep(100);
}catch (Exception e){
e.printStackTrace();
}
}
result=bf.toString();
} @Override
public String getResult() {
return result;
}
}
public class FutureData implements Data{ protected RealData realData=null;
protected boolean isReady=false; public synchronized void setRealData(RealData realData){
if(isReady){
return;
} this.realData=realData;
isReady=true;
notifyAll();
} @Override
public synchronized String getResult() {
while (!isReady){
try{
wait();
}catch (Exception e){
e.printStackTrace();
}
}
return realData.result;
}
}
public class Client { public Data request(final String queryStr){
final FutureData futureData=new FutureData();
new Thread(){
@Override
public void run(){
RealData realData=new RealData(queryStr);
futureData.setRealData(realData);
}
}.start(); return futureData; //立即返回了futureData
}
}
public class MainClass { public static void main(String[] args){
Client client=new Client();
Data data=client.request("name");
System.out.println("请求完毕");
try{
Thread.sleep(2000);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("数据="+data.getResult());
}
}