2017-11-29 31 views
2

나는 CompletableFuture 블록 스레드에서 get() 메서드를 알고 있지만 CompletableFuture가 완료 될 때까지이 문이 실행되기 때문에 Future가 처리되는 동안 System.out.println("xD")을 실행하는 방법을 어떻게 실행할 수 있습니까? 코드 :CompletableFuture 블록 메인 스레드

import java.util.concurrent.*; 
import java.util.stream.Stream; 

public class CompletableFutureTest { 


    public static void main(String[] args) throws ExecutionException, InterruptedException { 
     CompletableFuture.supplyAsync(CompletableFutureTest::counting).whenComplete((result, exception) -> { 
      if (exception != null) { 
       System.out.println(result); 
      } else { 
      } 
     }).get(); 

     System.out.println("xD"); 
    } 


    public static int counting() { 

     Stream.iterate(1, integer -> integer +1).limit(5).forEach(System.out::println); 
     try { 
      Thread.sleep(1000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     return 10; 
    } 
} 
+0

변수를 미래에 저장하고 인쇄하고 _then_ 'Future # get'을 호출하십시오. 결국 당신이 미래를 기다리고 있다면 당신은 무언가를 동시에 할 수 없습니다. 또한 메서드가 실패 할 경우에만 인쇄됩니다 (아마도'if'를 반대로해야합니다). – Rogue

+0

@Rogue 내가 미래를 기다릴 필요가 없다면 어떻게해야합니까? – masterofdisaster

답변

4

당신이 바로 인쇄 문 뒤에 get()를 이동해야합니다.
이렇게하면 future 값이 계산되는 동안 인쇄가 수행됩니다.

public static void main(String[] args) throws ExecutionException, InterruptedException { 
    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(CompletableFutureTest::counting).whenComplete((result, exception) -> { 
     if (exception != null) { 
      System.out.println(result); 
     } else { 
     } 
    }); 

    System.out.println("xD"); 
    Integer value = future.get(); 
}