completablefuture8742468051c85b06f0a0af9e3e506b5c 类在java中实现了 future8742468051c85b06f0a0af9e3e506b5c 接口。 completablefuture 可以被用作已经显式完成的future。 future 接口并没有提供很多功能,我们需要使用 get() 方法来获取异步计算的结果,该方法会被阻塞,因此没有办法以非阻塞的方式运行多个依赖任务,而 completablefuture 类可以提供链式运行多个依赖任务的功能,这些任务以异步的方式运行,因此我们可以创建一个任务链,在当前任务的结果可用时触发下一个任务。
语法public class completablefuture<t> extends object implements future<t>, completionstage<t>
example 翻译成中文为:示例import java.util.function.supplier;import java.util.concurrent.completablefuture;import java.util.concurrent.executionexception;public class completablefuturetest { public static void main(string args[]) throws executionexception, interruptedexception { calculator calc = new calculator(4, 7); completablefuture<integer> future = completablefuture.supplyasync(calc); future.thenaccept(result -> { system.out.println(result); }); system.out.println("completablefuturetest end.... "); thread.sleep(10000); }}// calculator classclass calculator implements supplier<integer> { private int x, y; public calculator(int x, int y) { this.x = x; this.y = y; } @override public integer get() { try { thread.sleep(3000); } catch(interruptedexception e) { e.printstacktrace(); } return x + y; }}
输出completablefuturetest end....11
以上就是java 9中completablefuture和future之间的区别是什么?的详细内容。
