【问题标题】:Java Akka's ActorRef async issuesJava Akka 的 ActorRef 异步问题
【发布时间】:2016-06-01 02:53:48
【问题描述】:

我已经开始使用 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 应该自动处理它:) 感谢您的想法!

【问题讨论】:

  • 我不确定我是否理解您的问题。任何时候只有一个线程可以执行给定的actor。
  • 澄清问题
  • @JosephStyons 请让他们编辑澄清。
  • @SotiriosDelimanolis 承认。抱歉有任何混淆。这个感觉就像一个很好的问题被埋在某个地方..
  • @JosephStyons 我的意思是,我假设了同样的事情,但是在编辑时,我们不应该做出可能改变问题含义的更改。

标签: java asynchronous akka


【解决方案1】:

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

因此,如果您创建两个 Hello 演员并向他们每个人发送一条消息,他们将同时处理它们。 (假设你的 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
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 2015-08-27
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多