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());;
}
}

 

你可能感兴趣的:(return,request,future,public,interface)