2016-11-04 3 views
0

У меня есть служба-исполнитель с пулом потоков из 10, и я ожидал, что я получу 10 заявлений распечатки, разделенных на три секунды, но я получаю только один вывод распечатки. Я передал 10 в качестве параметра, поэтому ожидал, что будет работать 10 потоков. Как я могу получить 10 будущих объектов?Исполнитель не возвращает 10 будущих объектов

public class Demo { 
    private static final ExecutorService executor = Executors.newFixedThreadPool(10); 

    public static void main (String[] args) throws ExecutionException, InterruptedException { 

     ArrayList futureObjects = new ArrayList(); 

     Callable<Integer> task =() -> { 
      try { 
       TimeUnit.SECONDS.sleep(3); 
       return 123; 
      } 
      catch (InterruptedException e) { 
       throw new IllegalStateException("task interrupted", e); 
      } 
     }; 

     System.out.println("Before execution of threads"); 

     Future<Integer> future = executor.submit(task); 

     Integer result = future.get(); 
     futureObjects.add(future.get()); 

     System.out.println("result: " + result); 

     for(Object futures : futureObjects){ 
      System.out.println("Futures in ArrayList: " + futures); 
     } 
    } 

} 

Выход я получаю:

Перед выполнением потоков

результат: 123

Фьючерсы в ArrayList: 123

+0

Вы посмотрели мой ответ? – developer

+0

Да, спасибо, кажется, что сон только приостанавливается в начале, а затем выплевывает все выходные 10 будущих объектов одновременно. Это не имеет значения только для наблюдения. –

ответ

2

Вы фактически добавили только одну задачу &, представленный на Threadpool, из-за которой одна задача выполнена & вернулся.

Вам необходимо отправить несколько задач вместе (используя Option1 или Option2 ниже), чтобы вы могли фактически использовать Threadpool (чтобы поддерживать поток занят).

Вы можете посмотреть на обновленную версию кода ниже:

Вариант (1): ExecutorService-invokeAll():

private static final ExecutorService executor = Executors.newFixedThreadPool(10); 

    public static void main (String[] args) throws ExecutionException, InterruptedException { 

     ArrayList futureObjects = new ArrayList(); 

     Callable<Integer> task =() -> { 
      try { 
       TimeUnit.MILLISECONDS.sleep(100); 
       return 123; 
      } 
      catch (InterruptedException e) { 
       throw new IllegalStateException("task interrupted", e); 
      } 
     }; 

     List<Callable<Integer>> callables = new ArrayList<>(); 
     callables.add(task); 
     callables.add(task); 
     callables.add(task); 
     callables.add(task); 
     //Add other tasks 

     System.out.println("Before execution of threads"); 

     List<Future<Integer>> futures = executor.invokeAll(callables); 

     for(Future future : futures){ 
      System.out.println("Futures in ArrayList: " + future.get()); 
     } 
    } 

Вариант (2): ExecutorService подать ():

private static final ExecutorService executor = Executors.newFixedThreadPool(10); 

    public static void main (String[] args) throws ExecutionException, InterruptedException { 

     ArrayList futureObjects = new ArrayList(); 

     Callable<Integer> task =() -> { 
      try { 
       TimeUnit.MILLISECONDS.sleep(100); 
       return 123; 
      } 
      catch (InterruptedException e) { 
       throw new IllegalStateException("task interrupted", e); 
      } 
     }; 

     List<Callable<Integer>> callables = new ArrayList<>(); 
     callables.add(task); 
     callables.add(task); 
     callables.add(task); 
     callables.add(task); 
     //Add other tasks 

     List<Future<Integer>> futures = new ArrayList<>(); 
     System.out.println("Before execution of threads"); 

     for(Callable<Integer> callable : callables) { 
      futures.add(executor.submit(callable)); 
     } 

     for(Future future : futures){ 
      System.out.println("Futures in ArrayList: " + future.get()); 
     } 
    } 

Вы можете обратиться к API here

1

Создано Executor будет пытаться выполнить задачи в 10 потоках параллельно, но каждая поставленная задача будет выполняться только один раз.