1 public interface Data { 2 3 String getRequest(); 4 } 5 6 7 public class RealData implements Data{ 8 9 private String result ; 10 11 public RealData (String queryStr){ 12 System.out.println("根据" + queryStr + "进行查询,这是一个很耗时的操作.."); 13 try { 14 Thread.sleep(5000); 15 } catch (InterruptedException e) { 16 e.printStackTrace(); 17 } 18 System.out.println("操作完毕,获取结果"); 19 result = "查询结果"; 20 } 21 22 @Override 23 public String getRequest() { 24 return result; 25 } 26 27 } 28 29 30 public class FutureData implements Data{ 31 32 private RealData realData ; 33 34 private boolean isReady = false; 35 36 public synchronized void setRealData(RealData realData) { 37 //如果已经装载完毕了,就直接返回 38 if(isReady){ 39 return; 40 } 41 //如果没装载,进行装载真实对象 42 this.realData = realData; 43 isReady = true; 44 //进行通知 45 notify(); 46 } 47 48 @Override 49 public synchronized String getRequest() { 50 //如果没装载好 程序就一直处于阻塞状态 51 while(!isReady){ 52 try { 53 wait(); 54 } catch (InterruptedException e) { 55 e.printStackTrace(); 56 } 57 } 58 //装载好直接获取数据即可 59 return this.realData.getRequest(); 60 } 61 62 63 } 64 65 66 public class FutureClient { 67 68 public Data request(final String queryStr){ 69 //1 我想要一个代理对象(Data接口的实现类)先返回给发送请求的客户端,告诉他请求已经接收到,可以做其他的事情 70 final FutureData futureData = new FutureData(); 71 //2 启动一个新的线程,去加载真实的数据,传递给这个代理对象 72 new Thread(new Runnable() { 73 @Override 74 public void run() { 75 //3 这个新的线程可以去慢慢的加载真实对象,然后传递给代理对象 76 RealData realData = new RealData(queryStr); 77 futureData.setRealData(realData); 78 } 79 }).start(); 80 81 return futureData; 82 } 83 84 } 85 86 87 public class Main { 88 89 public static void main(String[] args) throws InterruptedException { 90 91 FutureClient fc = new FutureClient(); 92 Data data = fc.request("请求参数"); 93 System.out.println("请求发送成功!"); 94 System.out.println("做其他的事情..."); 95 96 String result = data.getRequest(); 97 System.out.println(result); 98 99 } 100 }