piffy icon

Executor 3

piffy | PRO | 07/17/21 01:39:07 PM UTC | 0 ⭐ | 12564 👁️ | Never ⏰ | []
Java 5 |

0 B

|

None

|

0 👍

/

0 👎

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
 
public class Esempio3
{
    public static void main(String[] args) throws InterruptedException
    {
        ExecutorService executor = Executors.newFixedThreadPool(4);
 
        ArrayList<Future<Integer>> resultList = new ArrayList<>();
 
        for (int i = 1; i <= 10; i++) {
            Fattoriale calculator = new Fattoriale(i);
            Future<Integer> result = executor.submit(calculator);
            resultList.add(result);
        }
 
        executor.awaitTermination(5, TimeUnit.SECONDS);
 
        //provare anche con executor.shutdown(); e executor.shutdownNow();
        
        for (int i = 0; i < resultList.size(); i++)
        {
            Future<Integer> result = resultList.get(i);
            Integer number = null;
 
            try {
                if (result.isDone())
                    number = result.get();
            } catch (InterruptedException e) {}
              catch (ExecutionException e) {System.out.println("Dato non pronto");}
            System.out.printf("Main: Task %d: %d\n", i, number);
        }
 
        executor.shutdown();
    }
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎