Java Akka的ActorRef异步问题

时间:2016-06-01 02:53:49

标签: java asynchronous akka

我已经开始使用Akka与并发程序进行异步操作:

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;

public class TestAkka {

    public static void main(String[] args) throws InterruptedException {
        ActorSystem as1 = ActorSystem.create("actor1");
        ActorRef ar1 = as1.actorOf(Props.create(Hello.class));
        System.out.println("Start to say hello!");
        ar1.tell("Bob", ActorRef.noSender());
        ar1.tell("John", ActorRef.noSender());
        System.out.println("Finish to say hello!");
    }

    public static class Hello extends UntypedActor {

        @Override
        public void onReceive(Object message) throws Exception {
            if (message instanceof String) {
                System.out.println("Hello " + message);
                Thread.sleep(10000);  // <--Sim the job take a short time
            }
        }
    }
}

我执行上面的程序,系统必须逐个完成(不是并发):

ar1.tell("Bob", ActorRef.noSender());
ar1.tell("John", ActorRef.noSender());

结果是:

Hello Bob
(Wait 5 seconds)
Hello John
(Wait 5 seconds)

我想让它们并发,如何处理它?我希望Akka能自动处理它:)感谢你的想法!

1 个答案:

答案 0 :(得分:1)

Akka(以及一般的演员模型)的原则是在一个演员中,一切都按顺序发生。这有几个优点,包括演员在处理自己的可变状态时可以无锁。并发是通过让多个actor同时运行来实现的。

因此,如果您创建两个Hello个actor并向它们发送一条消息,它们将同时处理它们。 (假设你的akka​​执行上下文有足够的线程)。

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;

public class TestAkka {

    public static void main(String[] args) throws InterruptedException {
        ActorSystem as1 = ActorSystem.create("actor1");
        ActorRef ar1 = as1.actorOf(Props.create(Hello.class));
        ActorRef ar2 = as1.actorOf(Props.create(Hello.class));
        System.out.println("Start to say hello!");
        ar1.tell("Bob", ActorRef.noSender());
        ar2.tell("John", ActorRef.noSender());
        System.out.println("Finish to say hello!");
    }

    public static class Hello extends UntypedActor {

        @Override
        public void onReceive(Object message) throws Exception {
            if (message instanceof String) {
                System.out.println("Hello " + message);
                Thread.sleep(10000);  // <--Sim the job take a short time
            }
        }
    }
}