6

这是有效的代码。它向 Actor(Greeter)发送消息并等待回复。但它阻塞了当前线程。

public class Future1Blocking {

    public static void main(String[] args) throws Exception {

        ActorSystem system = ActorSystem.create("system");
        final ActorRef actorRef = system.actorOf(Props.create(Greeter.class), "greeter");

        Timeout timeout = new Timeout(Duration.create(5, "seconds"));
        Future<Object> future = Patterns.ask(actorRef, Greeter.Msg.GREET, timeout);

        // this blocks current running thread
        Greeter.Msg result = (Greeter.Msg) Await.result(future, timeout.duration());

        System.out.println(result);

    }
}

我的示例future.onSuccess在不阻塞当前调用线程的情况下获得结果的可能方法是什么?

4

1 回答 1

10

啊。这很容易(对不起)。

future.onSuccess(new PrintResult<Object>(), system.dispatcher());

在哪里:

public final class PrintResult<T> extends OnSuccess<T> {
    @Override public final void onSuccess(T t) {
        System.out.println(t);
    }
}
于 2013-05-17T15:27:29.807 回答