Akka Future_异步任务的执行
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());
}
}
运行结果,
system shutdown
1083962448
HelloWorld
从结果中,可以看出任务是异步执行的。
Maven依赖
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor_2.11</artifactId>
<version>2.3.8</version>
</dependency>
==============END==============