String result = f.get();
System.out.println(result);
可以通过CompletableFuture来控制多个异步操作同时执行:
CompletableFuture f = new CompletableFuture<>();
new Thread(() -> {
try {
System.out.println(“thread1:” + f.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
System.out.println(“thread2:” + f.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}).start();
f.complete(“hello”);
2.异步操作
创建异步操作的方法主要是:
public static CompletableFuture runAsync(Runnable runnable)
public static CompletableFuture runAsync(Runnable runnable,Executor executor)
public static CompletableFuture supplyAsync(Supplier supplier)
public static CompletableFuture supplyAsync(Supplier supplier,Executor executor)
使用如下:
CompletableFuture f = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return “hello”;
});
String