public static void main(String[] args) throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
System.out.println("first----"+Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(2); // comment the code
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello";
}).thenApply(s->{
System.out.println("second----"+Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return s+"World";
}).thenApply(a->{
System.out.println("third----"+Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
return a.toUpperCase();
});
System.out.println("time:"+(System.currentTimeMillis()-start)/1000);
System.out.println("result:"+future.get());
}
可以看出该程序是异步执行的,但是注释该代码后,结果发生了很大变化。该程序有时是异步的,有时是同步的,并且每个apply模块使用的线程。
会有所不同。是什么原因?