Java CompletableFuture(1)
private Long longTimeWork() {
try {
//模拟耗时操作,特意阻塞5秒。
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
return System.currentTimeMillis();
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("时间1:" + System.currentTimeMillis());
CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> longTimeWork());
System.out.println("时间2:" + System.currentTimeMillis());
Future<Long> f = future.whenComplete((v, a) -> {
System.out.println("时间3:" + System.currentTimeMillis());
System.out.println("v: " + v);
System.out.println("a: " + a);
System.out.println("时间4:" + System.currentTimeMillis());
});
System.out.println("时间5:" + System.currentTimeMillis());
}
输出:
06-12 16:28:23.157 4686-4686/zhangphil.test I/System.out: 时间1:1528792103157
06-12 16:28:23.161 4686-4686/zhangphil.test I/System.out: 时间2:1528792103161
06-12 16:28:23.162 4686-4686/zhangphil.test I/System.out: 时间5:1528792103162
06-12 16:28:28.164 4686-4710/zhangphil.test I/System.out: 时间3:1528792108164
06-12 16:28:28.165 4686-4710/zhangphil.test I/System.out: v: 1528792108164
a: null
时间4:1528792108165