2013-05-17 34 views
6

这是可行的代码。它发送消息给演员(Greeter)并等待回复。 但它会阻止当前线程。作为Akka演员的回应,处理Future onSuccess

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得到结果,而不会阻塞当前调用线程的可能呢?

回答

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); 
    } 
}