Akka Future_異步任務的執行java
akka 的 Future表示異步任務,任務的執行時異步的。以下代碼示例,異步
package com.usoft; import scala.concurrent.Future; import akka.dispatch.Futures; import akka.actor.ActorSystem; import akka.dispatch.OnSuccess; import java.util.concurrent.Callable; /** * Created by liyanxin on 2015/1/8. */ public class HelloFuture2 { public final static class PrintResult<T> extends OnSuccess<T> { @Override public final void onSuccess(T t) { System.out.println(t); } } public static void main(String args[]) { ActorSystem system = ActorSystem.create("mySystem"); /** * Future表示一個異步的任務,這個異步任務的執行由system.dispatcher()獲得的ExecutionContextExecutor執行 * Futures.future * Starts an asynchronous computation and returns a `Future` object with the result of that computation. * * The result becomes available once the asynchronous computation is completed. * * @param body the asychronous computation * @param executor the execution context on which the future is run * @return the `Future` holding the result of the computation */ Future<String> f = Futures.future(new Callable<String>() { public String call() throws InterruptedException { Thread.sleep(5000); return "Hello" + "World"; } }, system.dispatcher()); // system.dispatcher()返回一個ExecutionContextExecutor // 當異步任務執行成功時,打印執行結果 f.onSuccess(new PrintResult<String>(), system.dispatcher()); /** * This will stop the guardian actor, which in turn * will recursively stop all its child actors, then the system guardian * and the execute all registered termination handlers . */ system.shutdown(); System.out.println("system shutdown"); System.out.println(system.dispatcher().hashCode()); } }
運行結果,async
system shutdownide
1083962448spa
HelloWorldscala
從結果中,能夠看出任務是異步執行的。code
Maven依賴hash
<dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-actor_2.11</artifactId> <version>2.3.8</version> </dependency>
==============END==============it