并行JAVA程序设计模式Future模式

来源:互联网 发布:淘宝广告形式雷达 编辑:程序博客网 时间:2024/05/16 08:56
 
package future;public class Client {public Data request(final String queryStr) {final FutureData future = new FutureData();new Thread() {public void run() {RealData realdata = new RealData(queryStr);//真正的处理数据future.setRealData(realdata);//添加真数据}}.start();return future;}}

package future;public interface Data {public String getResult();}
package future;public class FutureData implements Data {<span style="white-space:pre"></span>protected RealData realdata = null;<span style="white-space:pre"></span>protected boolean isReady = false;<span style="white-space:pre"></span>public synchronized void setRealData(RealData realdata) {<span style="white-space:pre"></span>if (isReady) {<span style="white-space:pre"></span>return;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>this.realdata = realdata;<span style="white-space:pre"></span>isReady = true;<span style="white-space:pre"></span>notifyAll();//处理完毕,等待结束<span style="white-space:pre"></span>}<span style="white-space:pre"></span>@Override<span style="white-space:pre"></span>public synchronized String getResult() {<span style="white-space:pre"></span>while (!isReady) {//如果isReady为false则 继续等待<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>wait();<span style="white-space:pre"></span>} catch (InterruptedException e) {<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>return realdata.result;<span style="white-space:pre"></span>}}


package future;public class RealData implements Data {protected final String result;public RealData(String para) {StringBuffer sb = new StringBuffer();for (int i = 0; i < 10; i++) {sb.append(para+i);try {System.out.println("处理中"+i);Thread.sleep(100);} catch (InterruptedException e) {}}result = sb.toString();}@Overridepublic String getResult() {return result;}}


0 0
原创粉丝点击