2013-05-17 51 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); 
    } 
}