java并发编程之future模式
1、当你想并发去执行一段代码,但是还想获取这段代码的返回结果,那么future多线程模式就可以派上用场了,代码实现如下。
public class Client { public Data request() { final FutureData futureData = new FutureData(); new Thread(new Runnable() { @Override public void run() { futureData.setRealData(new RealData()); } }).start(); return futureData; } }
public interface Data { public String get(); }
public class FutureData implements Data{ private RealData realData = null; private boolean ok = false; public RealData getRealData() { return realData; } public synchronized void setRealData(RealData realData) { this.realData = realData; ok = true; notify(); } @Override public synchronized String get() { try { if(!ok) { this.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } return realData.get(); } }
public class RealData implements Data { public RealData() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public String get() { return "hello world!"; } }
public class main { public static void main(String[] args) { Client client = new Client(); Data data = client.request(); System.out.println(data.get()); } }
2、jdk1.5也提供了支持,代码如下。
public class RealData implements Callable<String> { public String call() throws Exception { int sum = 0; for(int i = 0; i < 100; i++) { sum += i; } return String.valueOf(sum); } }
public class main { public static void main(String[] args) throws InterruptedException, ExecutionException { FutureTask<String> futureTask = new FutureTask<String>(new RealData()); ExecutorService executor = Executors.newFixedThreadPool(1); executor.submit(futureTask); System.out.println(futureTask.get());; } }
本文出自 “温故而知新” 博客,请务必保留此出处http://fangchunliu.blog.51cto.com/1269779/1409599
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。