newCompletableFuture<Integer>().thenApplyAsync(newFunction<Integer,String>() { @OverridepublicStringapply(Integer integer) {// Do some heavy task herereturn"Something returned from long task"; }},Executors.newSingleThreadExecutor()).thenAcceptAsync(newConsumer<String>() { @Overridepublicvoidaccept(String s) {// Do something with result of previous task }}).thenRunAsync(newRunnable() { @Overridepublicvoidrun() {// Do something after everything ends }});
Here is another example in Android, how you can do some operation in background thread and return back to main thread when everything is completed.
newCompletableFuture<Integer>().thenApplyAsync(integer ->"Something returned from long task",Executors.newSingleThreadExecutor()).thenAcceptAsync(s -> {System.out.println("Previous result on main thread: "+ s); },ContextCompat.getMainExecutor(context));