2017-05-16 4 views
0

버튼을 클릭하면 사용자가 일부 계산을 수행하는 작업 (호출 가능)을 만듭니다. 작업이 끝나면 반응 할 수 있기를 원합니다. Future.get()을 사용하면 응용 프로그램을 차단합니다. Callable이 결과를 반환 할 때 반응 할 수있는 방법이 있습니까?차단하지 않고 Java 결과를 기다리는 중

private static void startTask(int i){ 
    try{ 
     Future<Integer> future = executor.submit(callables.get(i-1)); 
     ongoingTasks.put(i, future); 
     awaitResult(future, i); 
    } 
    catch(Exception e){ 
     e.printStackTrace(); 
    } 
} 

private static void awaitResult(Future<?> future, int taskNo) throws InterruptedException, ExecutionException{ 
    System.out.println("result : " + future.get()); 

    JButton b = buttons.get(taskNo); 
    b.setEnabled(false); 
} 
+1

가능한 복제 [하는 Future.get에 메소드 호출() 블록. 정말 바람직한가요?] (http://stackoverflow.com/questions/31092067/method-call-to-future-get-blocks-is-that-really-desirable) – aUserHimself

+0

계산은 두 번째 스레드에서 수행되어야합니다. 주 스레드 (또는 GUI 스레드)는 절대로 동결되지 않습니다. – Obenland

+0

로직을 넣고 다른 스레드에서 실행할 수 있도록 콜백을 만들면 –

답변

3

CompletableFuture과 같아 보입니다. 당신은 가치를 제공하는 "공급자"역할을합니다. 이것은 실제로 작업을 수행하는 함수입니다.

그러면 작업자가 완료 될 때마다이 값을 허용하는 함수가 있습니다.

이것은 모두 비동기식이므로 모든 결과는 결과에 관계없이 유지됩니다.

class Main 
{ 
    private static Integer work() { 
     System.out.println("work"); 
     return 3; 
    } 

    private static void done(Integer i) { 
     System.out.println("done " + i); 
    } 

    public static void main (String... args) 
    { 
     CompletableFuture.supplyAsync(Main::work) 
         .thenAccept(Main::done); 

     System.out.println("end of main"); 
    } 
} 

샘플 출력 :의

end of main 
work 
done 3 
+0

불행히도 나는 ExecutorService – cAMPy