作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我希望我的 Actor 等待某些事件发生,但我希望它仍然接收消息并继续处理消息。我怎样才能实现它?
我的代码如下:
class MyActor extends UntypedActor {
//onReceive implementation etc...
private void doSomething(ActorRef other){
String decision = (String) Await.result(ask(other, new String("getDecision"),1000), Duration.create(1, SECONDS));
while(decision.equals(""){
Thread.sleep(100)
decision = (String) Await.result(ask(other, new String("getDecision"),1000), Duration.create(1, SECONDS));
}
}
}
但这会阻止整个参与者,直到它收到正确的决定为止。我怎样才能在不妨碍我的 Actor 的情况下实现类似的目标?
最佳答案
这种代码非常适合使用 Futures
。
您可以在这里找到更多信息:http://doc.akka.io/docs/akka/snapshot/java/futures.html
就您而言,它看起来像:
final ExecutionContext ec = context().dispatcher();
private void doSomething(ActorRef other){
Future<Object> decision = (Patterns.ask(other, new String("getDecision"), 1000));
decision.onSuccess(new OnSuccess<Object>() {
public void onSuccess(Object result) {
String resultString = (String) result;
System.out.println("Decision: " + result);
}
}, ec);
}
您应该始终尝试避免 Await.result
正如您所说,这会导致线程阻塞。您可以使用 onSuccess
或 onComplete
等回调在 future 返回后执行代码,而无需等待结果。
关于java - 如何在不阻塞的情况下等待事件发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27748555/
我是一名优秀的程序员,十分优秀!