如何在不使用Thread.sleep命令的情况下在akka actor中执行整个代码?

时间:2015-11-17 16:14:06

标签: java akka

我有一个样本akka代码

public class MainSystem {
  public static void main(String... args) throws Exception {
        final ActorSystem actorSystem = ActorSystem.create("actor-system");
        Thread.sleep(5000);
        final ActorRef actorRef = actorSystem.actorOf(SimpleActor.props(10));
        final ActorRef actorRef2 = actorSystem.actorOf(ActorTwo.props(10));
        System.out.println("actorref2:  "+actorRef2);

        actorRef2.tell(new Command("actor two cmd"), null);

        actorRef.tell(new Command("CMD 1"), null);
        actorRef.tell(new Command("CMD 2"), null);

        actorRef2.tell(new Command("actor two cmd   second"), null);


        actorRef.tell(new Command("CMD 3"), null);
        actorRef.tell(new Command("CMD 4"), null);
        actorRef.tell(new Command("CMD 5"), null);

        Thread.sleep(5000);

        actorSystem.shutdown();
    }
}

如果我避开上一个sleep语句,代码将不会完全执行。如何在不使用睡眠的情况下编写程序来完成演员中的所有代码?

1 个答案:

答案 0 :(得分:2)

您可以在收到并处理完最后一条消息后从actor内部关闭系统,并等待actorSystem.awaitTermination()终止。

修改

Shut Down Patterns in Akka是一个很好的博客,解释了关机模式。你现在可能不需要这么多,但你会得到一个要点。代码在scala中,但并不复杂。