- 概述,Future模式是多线程开发中比较常见模式,核心思想是异步调用,思路是执行函数时,马上得到返回结果,但是并不急于处理,而去执行其它业务逻辑,最后再使用比较慢的数据,就不存在无谓的等待,充分利用的所有的时间片段。提高响应速度
- FutureData
public class FutureData implements Data {
protected RealData realdata=null; //FutureData是真实数据包装
protected boolean isReady=false;
public synchronized void setRealdata(RealData realdata) {
if (isReady) {
return;
}
this.realdata=realdata;
isReady=true;
notifyAll(); //数据完成,通知getResult
}
@Override
public String getResult() {
// TODO Auto-generated method stub
while(!isReady)
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return realdata.result;
}
}
3.RealData
public class RealData implements Data {
protected final String result;
public RealData(String para) {
// TODO Auto-generated constructor stub
StringBuffer sb=new StringBuffer();
for(int i=0;i<5;i++)
{
sb.append(para);
try {
Thread.sleep(1000); //模拟很慢的加载速度
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("数据完成");
System.out.println(System.currentTimeMillis()/1000);
result=sb.toString();
}
@Override
public String getResult() {
// TODO Auto-generated method stub
return result;
}
}
4.Data
public interface Data {
public String getResult();
}
5.client
public class Client {
public Data request (final String querystr)
{
final FutureData futureData=new FutureData();
new Thread(){
public void run() {
RealData realData=new RealData(querystr);
futureData.setRealdata(realData);
};
}.start();
return futureData;
}
}
6.Main
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Client client=new Client();
Data data=client.request("name");
System.out.println("请求完毕");
try {
Thread.sleep(7000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(System.currentTimeMillis()/1000);
System.out.println("数据"+data.getResult());
}
}
7.参考自java高并发程序设计