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

最佳答案

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

10-08 09:07
查看更多