Akka java - 同步儿童演员

时间:2015-05-23 12:59:36

标签: java akka


我刚刚开始使用Akka(在Java中),我遇到了一个我不知道如何解决的问题。

我有N名球员和一名神谕。 一旦创建,所有玩家必须与必须响应"赢家/输家"的oracle沟通。

问题在于我不知道轮流,一次一个地传达球员的策略:
例如:player1 - > player2 - > player3 - > player1 - >播放器2 - > ......

球员班:

public class MyPlayers extends UntypedActor {

/*
* I created one context of N Player
*/
public MyPlayers() { }

public void preStart() {
    //in this way all N players at the beginning, start to communicate concurrently.
    ActorSelection oracle = getContext().actorSelection("//Main/user/app/oracle"); 
    oracle.tell(new MyMessage(myValue), getSelf());
}

@Override
public void onReceive(Object msg) throws Exception {

    if (msg instanceof MyMessage) {
        //do something
        sender().tell(MyMessage, getSelf());

    }


    if (msg instanceof DoneMsg) {
        if (((DoneMsg) msg).isDone()) {
            log("Stop Players");
            getContext().stop(getSelf());
        }
    }

}

Oracle类:

public class Oracle extends UntypedActor {
private int nPlayers;
public Oracle(int nPlayers) {
    this.nPlayers = nPlayers;
}

public void preStart() {
    stateGame = false;  //When the play starter, there is not any wins.
}

@Override
public void onReceive(Object msg) throws Exception {

    if (msg instanceof MyMessage) {
        if (!stateGame) {
            //do something
            sender().tell(MyMessage, getSelf());
        }
        else {
            //do something
            getContext().stop(getSelf());
        }
    }
}

通过排除竞争来有条不紊地沟通球员的最佳策略是什么?

感谢所有人。

1 个答案:

答案 0 :(得分:0)

以有序的方式向演员发送消息的基本两个选项:
1.循环路由器,玩家在路线上 2.包含对玩家的引用并迭代它们的数组或集合

无关的说明:
避免演员选择。通过构造函数/道具或消息将oracle引用传递给玩家。选择很少是合理的(主要是用于远程处理),这是一种危险的做法。