我想我已经找到了解决我自己问题的更好方法。我可以向参与者发送更高优先级的退出消息,而不是使用 volatile 变量让操作知道何时死亡。它看起来像这样:
val a = new Actor() {
def act():Unit = {
loop{ react {
case "Exit" => exit(); return;
case MyMessage => {
//this check makes "Exit" a high priority message, if "Exit"
//is on the queue, it will be handled before proceeding to
//handle the real message.
receiveWithin(0) {
case "Exit" => exit(); return
case TIMEOUT => //don't do anything.
}
sender ! "hi!" //reply to sender
}
}}
}
}
a.start()
val f = a !! MyMessage
while( ! f.isSet && a.getState != Actor.State.Terminated ) {
//will probably return almost immediately unless the Actor was terminated
//after I checked.
Futures.awaitAll(100,f)
}
if( a.getState != Actor.State.Terminated ) {
f() // the future should evaluate to "hi!"
}
a ! "Exit" //stops the actor from processing anymore messages.
//regardless of if any are still on the queue.
a.getState // terminated
可能有一种更简洁的方法来编写这个..但这大约是我在我的应用程序中所做的。
reactWithin(0) 是立即无操作,除非队列上有“退出”消息。队列中的“退出”消息替换了我将在线程 Java 应用程序中放入的 volatile 布尔值。