public class CompletableFutureDemo {
public static CompletableFuture<String> doOneThing() {
return
CompletableFuture.supplyAsync(() -> {
try
{
Thread.sleep(2000);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
return
"doOneThing"
;
});
}
public static CompletableFuture<String> doOtherThing(String parameter) {
return
CompletableFuture.supplyAsync(() -> {
try
{
Thread.sleep(2000);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
return
parameter +
" "
+
"doOtherThing"
;
});
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
StopWatch stopWatch =
new
StopWatch(
"CompletableFutureDemo"
);
stopWatch.start();
testCompletableFuture();
stopWatch.stop();
System.out.println(stopWatch);
}
private static void testCompletableFuture() throws InterruptedException, ExecutionException {
CompletableFuture<String> resultFuture = doOneThing().thenCompose(CompletableFutureDemo::doOtherThing);
String doOneThingResult = resultFuture.get();
System.out.println(
"DoOneThing and DoOtherThing execute finished. result = "
+ doOneThingResult);
}
}