Akka Future_异步任务的执行

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==============

转载于:https://my.oschina.net/xinxingegeya/blog/365230

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值