Future模式
/** * qccr.com Inc. * Copyright (c) 2014-2016 All Rights Reserved. */ package com.youqianhuan.future; /** * 数据处理接口 * @author chenghuanhuan@qccr.com * @since $Revision:1.0.0, $Date: 2017年03月05日 上午9:54 $ */ public interface Data { /** * 获取请求数据 * @return */ Object getReuqestData(); }
/** * qccr.com Inc. * Copyright (c) 2014-2016 All Rights Reserved. */ package com.youqianhuan.future; /** * @author chenghuanhuan@qccr.com * @since $Revision:1.0.0, $Date: 2017年03月05日 上午9:58 $ */ public class RealData implements Data { // 处理结果 private Object result; public RealData(String request){ // 处理真实逻辑 System.out.println("处理真实逻辑!"); execute(request); } public Object getReuqestData() { return result; } public void execute(String data){ System.out.println("处理中....1"); try { Thread.sleep(1000); System.out.println("处理中....2"); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } result = data; } }
/** * qccr.com Inc. * Copyright (c) 2014-2016 All Rights Reserved. */ package com.youqianhuan.future; /** * @author chenghuanhuan@qccr.com * @since $Revision:1.0.0, $Date: 2017年03月05日 上午9:56 $ */ public class FutureData implements Data { private RealData realData; private boolean isReady = false; /** * 设置真实的处理类 * @param realData */ public synchronized void setRealData(RealData realData){ if (isReady){ return; } this.realData = realData; isReady = true; // 进行通知 notify(); } /** * 获取处理结果 * @return */ public synchronized Object getReuqestData() { while (!isReady){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } return this.realData.getReuqestData(); } }
/** * qccr.com Inc. * Copyright (c) 2014-2016 All Rights Reserved. */ package com.youqianhuan.future; /** * 处理客户端 * @author chenghuanhuan@qccr.com * @since $Revision:1.0.0, $Date: 2017年03月05日 上午9:52 $ */ public class FutureClient { public static Data reuquest(final String request){ final FutureData futureData = new FutureData(); new Thread(new Runnable() { public void run() { RealData realData = new RealData(request); futureData.setRealData(realData); } }).start(); return futureData; } }
/** * qccr.com Inc. * Copyright (c) 2014-2016 All Rights Reserved. */ package com.youqianhuan.future; /** * @author chenghuanhuan@qccr.com * @since $Revision:1.0.0, $Date: 2017年03月05日 上午10:17 $ */ public class Main { public static void main(String[] args) { Data futureData = FutureClient.reuquest("hahhahah"); System.out.println(futureData.getReuqestData()); } }