Future模式
创建1~n个线程执行别的异步任务,并可要求这些线程返回异步任务的执行结果。
code
package concurrent;
import java.util.concurrent.*;
public class C12_FuturePattern {
static class RealData implements Callable<String>{
private String data;
public RealData(String data){ this.data = data; }
@Override
public String call() throws Exception {
Thread.sleep(2000); //模拟任务
return data.toUpperCase();
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
//1.创建线程池
ExecutorService es = Executors.newFixedThreadPool(1);
//2.提交一个实现了Callable接口的任务并立即返回
Future<String> future = es.submit(new RealData("abcdefg"));
System.out.println("task was submit.");
//3.主线程做其他事情
doOtherWork();
//4.主线程通过future获取所提交任务返回的数据,若还没完成那么会在get函数出阻塞
System.out.println(future.get());
es.shutdown();
}
public static void doOtherWork(){
System.out.println("other work was completed, wait for future.get().");
}
}
console
task was submit.
other work was completed, wait for future.get().
ABCDEFG