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模型
Actor模型=数据+行为+消息。
Actor模型内部的状态由自己的行为维护,外部线程不能直接调用对象的行为,必须通过消息才能激发行为,这样就保证Actor内部数据只有被自己修改。