转载:https://blog.csdn.net/liubenlong007/article/details/54093794
我们都知道在编写java线程的时候,要传递不可变对象,这里akka也是如此
下面这个例子就是传递不可变对象:
package akka.unmodifiable;
import java.util.Collections;
import java.util.List;
/**
* Created by liubenlong on 2017/1/5.
*
* actor中传递的对象要是不可变对象。当然是为了安全了
*/
public final class Message {
private final int age;
private final List list;
public Message(int age, List list){
this.age = age;
/**
* 把普通list包装为不可变对象
*/
this.list = Collections.unmodifiableList(list);
}
public int getAge() {
return age;
}
public List getList() {
return list;
}
}
package akka.unmodifiable;
import akka.actor.UntypedActor;
import com.alibaba.fastjson.JSONObject;
public class Greeter extends UntypedActor {
@Override
public void onReceive(Object msg) throws InterruptedException {
try {
System.out.println("Greeter收到的数据为:" + JSONObject.toJSONString(msg));
getSender().tell("Greeter工作完成。", getSelf());//给发送至发送信息.
}catch (Exception e){
e.printStackTrace();
}
}
}
package akka.unmodifiable;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import com.alibaba.fastjson.JSONObject;
import java.util.Arrays;
public class HelloWorld extends UntypedActor {
ActorRef greeter;
@Override
public void preStart() {
// create the greeter actor
greeter = getContext().actorOf(Props.create(Greeter.class), "greeter");
System.out.println("Greeter actor path:" + greeter.path());
// tell it to perform the greeting
greeter.tell(new Message(2, Arrays.asList("2", "dsf")), getSelf());
}
@Override
public void onReceive(Object msg) {
try {
System.out.println("HelloWorld收到的数据为:" + JSONObject.toJSONString(msg));
}catch (Exception e){
e.printStackTrace();
}
}
}
package akka.unmodifiable;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import com.typesafe.config.ConfigFactory;
public class Main {
// public static void main(String[] args) {
// akka.Main.main(new String[] { HelloWorld.class.getName() });
// }
public static void main(String[] args) {
//创建ActorSystem。一般来说,一个系统只需要一个ActorSystem。
//参数1:系统名称。参数2:配置文件
ActorSystem system = ActorSystem.create("Hello", ConfigFactory.load("akka.config"));
ActorRef a = system.actorOf(Props.create(HelloWorld.class), "helloWorld");
System.out.println(a.path());
}
}