Java 9中CompletableFuture和Future之间的区别是什么?
CompletableFuture
语法
<strong>public class CompletableFuture<T> extends Object implements Future<T>, CompletionStage<T></strong>
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); <strong>CompletableFuture<Integer></strong> future = CompletableFuture.<strong>supplyAsync</strong>(calc); future.<strong>thenAccept</strong>(result -> { System.out.println(result); }); System.out.println("CompletableFutureTest End.... "); Thread.sleep(10000); } } <strong>// Calculator class</strong> class Calculator implements <strong>Supplier<Integer></strong> { private int x, y; public Calculator(int x, int y) { this.x = x; this.y = y; } <strong>@Override</strong> public Integer get() { try { Thread.sleep(3000); } catch(InterruptedException e) { e.printStackTrace(); } return x + y; } }
输出
<strong>CompletableFutureTest End.... 11</strong>
以上就是Java 9中CompletableFuture和Future之间的区别是什么?的详细内容,更多请关注其它相关文章!