lundi 22 juillet 2019

Why does the order of output not getting changed when using random and threadpool?

I am trying to learn about using threadpool thru Executors. I am trying to print the factorial result of 10 numbers from 1 to 10 and then i let the thread sleep for 1-5 seconds which will chosen as randomly.

Here is my Callable Task

    @Override
    public Integer call() throws Exception {
        int i= 1, temp = num;
        while (temp > 1){
            i = i*temp;
            temp--;
        }
        int x = ThreadLocalRandom.current().nextInt(1, 6);
        Thread.sleep(x * 1000);
        return i ;
    }

Here is my main class:

public static void main(String[] args) throws InterruptedException, ExecutionException {
    ExecutorService e = Executors.newFixedThreadPool(10);
    Set <Future<Integer>> set= new HashSet<Future<Integer>>();
    int totalSum = 0;
    for (int i = 1; i <= 10; i++) {
        set.add(e.submit(new FactorialCalculator(i)));
    }
    while(!set.isEmpty()) {
        Iterator<Future<Integer>> iter =  set.iterator();
        Future<Integer> fi = iter.next();
        if(fi.isDone()) {
            int temp = fi.get();
            System.out.println(temp);
            iter.remove();  
        }   
    }
}

I ran this program on Eclipse 10 times, output remains same everytime.

Then i compile it thru command prompt and then ran it there. Output came different from eclipse but again running multiple times will produce same output here.

Why the ouput doesn't come randomly?

Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire