在akka中使用代码并使用msg ()需要理解为什么它只接收第一个msg,然后忽略.
package ping_pong;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
public class PingPongActor extends AbstractActor {
public static void main(String[] args) throws Exception {
ActorSystem _system = ActorSystem.create("PingPongActorApp");
ActorRef masterpp = _system.actorOf(Props.create(PingPongActor.class), "pp");
masterpp.tell(PING, masterpp);
System.out.println("after first msg");
masterpp.tell(PING, masterpp);
masterpp.tell(PING, masterpp);
masterpp.tell(PING, masterpp);
masterpp.tell(PING, masterpp);
masterpp.tell(PING, masterpp);
System.out.println("last msg");
}
static String PING = "PING";
static String PONG = "PONG";
int count = 0;
@Override
public Receive createReceive() {
return receiveBuilder().match(String.class, ua -> {
if (ua.matches(PING)) {
System.out.println("PING" + count);
count += 1;
Thread.sleep(100);
if (count <= 10) {
getSelf().tell(PONG, getSelf());
}
getContext().become(receiveBuilder().match(String.class, ua1 -> {
if (ua1.matches(PONG)) {
System.out.println("PONG" + count);
count += 1;
Thread.sleep(100);
getContext().unbecome();
}
}).build());
if (count > 10) {
System.out.println("DONE" + count);
getContext().stop(getSelf());
}
}
}
).build();
}
}它给出了结果:
PingPongActorApp-akka.actor.default-dispatcher-4 INFO akka.event.slf4j.Slf4jLogger - Slf4jLogger在第一个msg最后一个msg PING0 PONG1之后启动。
问题是,为什么它忽略了其他的乒乓或乒乓球信息.?
发布于 2022-11-15 01:29:19
当您getContext().become时,您将整个Receive替换为该演员,因此
getContext().become(receiveBuilder().match(String.class, ua1 -> {
if (ua1.matches(PONG)) {
System.out.println("PONG" + count);
count += 1;
Thread.sleep(100);
getContext().unbecome();
}
}).build());您正在安装一个Receive,它只响应与PONG匹配的消息。
顺便说一句:Thread.sleep基本上是您在一个参与者中所能做的最糟糕的事情,因为它阻止了参与者做任何事情,同时也消耗了一个分派程序线程。在100Millis中给自己安排一条消息,然后触发unbecome,这将是一个更好的主意。
https://stackoverflow.com/questions/74437564
复制相似问题