起因
得到ActorRef就可以给actor发送消息,但无法接收多回复,也不知道actor是否停止
Inbox收件箱出现就是解决这两个问题
示例
package akka.demo.actor import akka.actor.* import java.time.Duration /** ** created by tankx ** 2019/9/12 与actor 通信模式ask或tell 无法支持接收多回复和观察其它actor的生命周期,所以inbox应用而生 **/ fun main() { val system = ActorSystem.create("box-sys") val helloActor = system.actorOf(HelloActor.props("tom")) helloActor.tell("hi", ActorRef.noSender()) val box = Inbox.create(system) box.send(helloActor, "how are you!") box.watch(helloActor)//监控actor 的生命周期,当actor stop, receive会接收到Terminated消息 helloActor.tell(PoisonPill.getInstance(), ActorRef.noSender());//毒死actor while (true) { try { val receiveObj = box.receive(Duration.ofSeconds(2))//可一直接收actor回的消息 println("box receive:" + receiveObj) if (receiveObj is Terminated) { break } } catch (e: Exception) { println(e.message) } } Thread.sleep(2000) System.exit(1) }