Advertisement
piffy

Executor 3

Jul 17th, 2021
2,666
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.34 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.concurrent.ExecutionException;
  4. import java.util.concurrent.ExecutorService;
  5. import java.util.concurrent.Executors;
  6. import java.util.concurrent.Future;
  7. import java.util.concurrent.TimeUnit;
  8.  
  9. public class Esempio3
  10. {
  11.     public static void main(String[] args) throws InterruptedException
  12.     {
  13.         ExecutorService executor = Executors.newFixedThreadPool(4);
  14.  
  15.         ArrayList<Future<Integer>> resultList = new ArrayList<>();
  16.  
  17.         for (int i = 1; i <= 10; i++) {
  18.             Fattoriale calculator = new Fattoriale(i);
  19.             Future<Integer> result = executor.submit(calculator);
  20.             resultList.add(result);
  21.         }
  22.  
  23.         executor.awaitTermination(5, TimeUnit.SECONDS);
  24.  
  25.         //provare anche con executor.shutdown(); e executor.shutdownNow();
  26.        
  27.         for (int i = 0; i < resultList.size(); i++)
  28.         {
  29.             Future<Integer> result = resultList.get(i);
  30.             Integer number = null;
  31.  
  32.             try {
  33.                 if (result.isDone())
  34.                     number = result.get();
  35.             } catch (InterruptedException e) {}
  36.               catch (ExecutionException e) {System.out.println("Dato non pronto");}
  37.             System.out.printf("Main: Task %d: %d\n", i, number);
  38.         }
  39.  
  40.         executor.shutdown();
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement