2014-03-08 3 views
0

프로그램 완료시 Java ExecutorCompletionService에 문제가 있습니다.ExecutorCompletionService가 응답하지 않습니다.

내 실제 프로그램에서 수많은 작업을 실행하고 완료된 첫 번째 결과를 얻고 싶기 때문에 ExecutorService 대신 ExecutorCompletionService을 사용해야합니다.

슬프게도 모든 작업이 처리 되었더라도 슬프게도 내 프로그램이 멈추는 것을 발견했습니다.

나는 실행할 때 멈추는 작은 예제를 만들었습니다.

import java.util.concurrent.*; 

public class Debug { 

    public static void main(String[] args) { 
     CompletionService<String> compService = new ExecutorCompletionService<>(Executors.newFixedThreadPool(2)); 

     for (int i = 0; i < 2; i++) { 
      compService.submit(new Task(i)); 
     } 

     for (int i = 0; i < 2; i++) { 
      try { 
       String result = compService.take().get(); 
       System.out.println("RESULT: " + result); 
      } catch (ExecutionException | InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    private static class Task implements Callable<String> { 

     private final int number; 

     public Task(int number) { 
      this.number = number; 
     } 

     @Override 
     public String call() throws Exception { 
      return "Number " + number; 
     } 
    } 
} 

누군가 내가 잘못하고있는 것을 지적하면 매우 감사 할 것입니다.

감사합니다.

답변

4

그것은 단순히 응답 당신은 실행기가 종료 될 때까지 (새 작업이 실행 대기) 계속 실행 스레드를 사용하는 실행기를 시작했기 때문에 :

ExecutorService executor = Executors.newFixedThreadPool(2); 
    CompletionService<String> compService = new ExecutorCompletionService<>(executor); 

    for (int i = 0; i < 2; i++) { 
     compService.submit(new Task(i)); 
    } 

    for (int i = 0; i < 2; i++) { 
     try { 
      String result = compService.take().get(); 
      System.out.println("RESULT: " + result); 
     } catch (ExecutionException | InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 

    executor.shutdownNow(); 
관련 문제