java現存的異步編程大致分爲兩種 :
通過回調方式控制實現
public static void callback() throws InterruptedException, ExecutionException {
CompletableFuture<String> resultFuture = CompletableFuture.supplyAsync(() -> {
System.out.println("callback" + ":" + Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("completableFuture complete");
return "hello completablefuture";
});
System.out.println(" main thread complete");
// 回調獲取執行結果 thenAccept使用同一線程執行任務,並獲取結果,thenAcceptAsync使用不同線程
resultFuture.thenAcceptAsync((m) -> {
System.out.println("callback:" + m + ":" + Thread.currentThread());
System.out.println("Get Result by Back Function ");
});
System.out.println(" ========");
//resultFuture.get();
//System.out.println("------------ " + resultFuture.get());
}
actor模型