1. 程式人生 > >akka學習教程(二)HelloWord

akka學習教程(二)HelloWord

akka系列文章目錄

注意:新版本的akka需要使用jdk8

裡面有兩個Actor:

package sample.hello;

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

public class HelloWorld extends UntypedActor {

  @Override
  public void preStart() {
    // create the greeter actor
    final ActorRef greeter = getContext().actorOf(Props.create(Greeter.class), "greeter"
); // tell it to perform the greeting greeter.tell(Greeter.Msg.GREET, getSelf()); } @Override public void onReceive(Object msg) { if (msg == Greeter.Msg.DONE) { // when the greeter is done, stop this actor and with it the application getContext().stop(getSelf()); } else
unhandled(msg); } }
package sample.hello;

import akka.actor.UntypedActor;

public class Greeter extends UntypedActor {

  public static enum Msg {
    GREET, DONE;
  }

  @Override
  public void onReceive(Object msg) throws InterruptedException {
    if (msg == Msg.GREET) {
      System.out.println("Hello World!"
); Thread.sleep(1000); getSender().tell(Msg.DONE, getSelf()); } else unhandled(msg); } }

main方法

package sample.hello;

public class Main {

  public static void main(String[] args) {
    akka.Main.main(new String[] { HelloWorld.class.getName() });
  }
}

另一種main寫法,通過建立actor的方式

 public static void main(String[] args) {
    ActorSystem system = ActorSystem.create("Hello");
    ActorRef a = system.actorOf(Props.create(HelloWorld.class), "helloWorld");
    System.out.println(a.path());
  }

helloWord示例比較簡單,不過多解釋

參考資料

  • 書籍《java高併發程式設計》