package com.example.app;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
public class CompletableFutureTest {
public static void main(String[] args) {
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new Random().nextInt(100);
}).whenComplete((value1,throwable) -> {
System.out.println("value in async task: " + value1);
});
System.out.println("main thread goes on its execution......");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main thread exits......");
}
}
说明: CompletableFuture的whenComlete方法是异步回调方法,当任务执行完成时才会调用,调用whenComplte方法不会阻止主线程的继续运行,这一点和FutureTask的get()方法完全不同,Future接口里定义的get方法是同步阻塞的。