简体   繁体   中英

how can i execute whole code in akka actor without using the Thread.sleep command?

i have a sample akka code

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();
    }
}

If i avoid the last sleep statement, the code will not execute completely. How can i write program to complete all codes in actor without using sleep ?

You could shutdown the system from inside the actor after the last message is received and processed, and wait for termination using actorSystem.awaitTermination() .

Edit

Shut Down Patterns in Akka is a nice blog explaining a shutdown pattern. You may not need this much now, but you will get a gist. The code is in scala, but its not that complicated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM