码迷,mamicode.com
首页 > 编程语言 > 详细

java并发编程之future模式

时间:2014-05-13 01:29:02      阅读:405      评论:0      收藏:0      [点我收藏+]

标签:interface   request   future   return   public   

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

java并发编程之future模式,布布扣,bubuko.com

java并发编程之future模式

标签:interface   request   future   return   public   

原文地址:http://fangchunliu.blog.51cto.com/1269779/1409599

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!