首页 > 代码库 > java并发编程之future模式

java并发编程之future模式

1、当你想并发去执行一段代码,但是还想获取这段代码的返回结果,那么future多线程模式就可以派上用场了,代码实现如下。

public class Client {
public Data request() {
final FutureData futureData = http://www.mamicode.com/new FutureData();>
public interface Data {
public String get();
}
public class FutureData implements Data{
private RealData realData = http://www.mamicode.com/null;>
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 = http://www.mamicode.com/client.request();>

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