Future异步回调
public class TestFutura2 {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
//任务c1放入线程池并行执行
C1 c1 = new C1();
Future<Double> future = pool.submit(c1);
pool.shutdown();
System.out.println("继续执行主线程任务");
//等待执行结果
Double r = future.get();
System.out.println("确认r1任务已结束,并得到了执行结果: "+r);
}
static class C1 implements Callable<Double> {
@Override
public Double call() throws Exception{
Thread.sleep(3000);
return Math.random();
}
}
}
运行结果:
继续执行主线程任务
确认r1任务已结束,并得到了执行结果: 0.7236221399198196
CompletableFuture
public class CompletableFutureDemo {
public static void main(String[] args) {
//线程回调
CompletableFuture<Object> cf = new CompletableFuture<>();
for (int i = 0; i < 5; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"阻塞等待执行结果");
try{
//cf.get() 阻塞获取命令信息
System.out.println(Thread.currentThread().getName()+"获取执行结果---->"+cf.get());
}catch (Exception e){ }
},"线程-"+i).start();
}
new Thread(()->{
try{
TimeUnit.SECONDS.sleep(2);
//解除阻塞,继续执行cf.get方法之后的代码,并获取结果
cf.complete(Math.random());
}catch (Exception e){ }
}).start();
}
}
输出结果:
线程-0阻塞等待执行结果
线程-3阻塞等待执行结果
线程-2阻塞等待执行结果
线程-1阻塞等待执行结果
线程-4阻塞等待执行结果
线程-1获取执行结果---->0.1804630976805568
线程-3获取执行结果---->0.1804630976805568
线程-2获取执行结果---->0.1804630976805568
线程-4获取执行结果---->0.1804630976805568
线程-0获取执行结果---->0.1804630976805568