标签:data syn 查询 ack void main control for 客户端
Main
package com.cmos.ngkm.web.controller.basic; public class Main { public static void main(String[] args) throws InterruptedException{ FutureClient fc = new FutureClient(); Data data = fc.request("请求参数"); System.out.println("请求发送成功!"); System.out.println("做其它的事情..."); String result = data.getRequest(); System.out.println(result); } }
FutureClient
package com.cmos.ngkm.web.controller.basic; public class FutureClient { public Data request(final String queryStr){ //1.我想要一个代理对象(Data接口的实现类)先返回给发送请求的客户端,告诉他请求已经接收到,可以做其他事情 final FutureData futureData = new FutureData(); //2.启动一个新的线程,去加载真实的数据,传递给这个代理对象 new Thread(new Runnable() { @Override public void run() { //这个新的线程可以去慢慢的加载真实对象,然后传递给代理对象 RealData realData = new RealData(queryStr); futureData.setRealData(realData); } }).start(); return futureData; } }
FutureData
package com.cmos.ngkm.web.controller.basic; import groovy.transform.Synchronized; public class FutureData implements Data{ private RealData realData; private boolean isReady = false; @Override public synchronized String getRequest() { while(!isReady) { try{ wait(); }catch(InterruptedException e){ e.printStackTrace(); } } return this.realData.getRequest(); } public synchronized void setRealData(RealData realData) { if(isReady) { return; } this.realData = realData; isReady = true; notify(); } }
RealData
package com.cmos.ngkm.web.controller.basic; public class RealData implements Data{ private String result; public RealData(String queryStr){ System.out.println("根据"+queryStr+"进行查询,这是一个很耗时的操作..."); try{ Thread.sleep(5000); }catch(InterruptedException e) { e.printStackTrace(); } result = "查询结果"; } @Override public String getRequest() { return result; } }
Data
package com.cmos.ngkm.web.controller.basic; public interface Data { String getRequest(); }
标签:data syn 查询 ack void main control for 客户端
原文地址:http://www.cnblogs.com/gyll/p/7894508.html