I am trying to learn about using threadpool through Executors.
I am trying to print the factorial result of 10
numbers from 1 to 10 (not necessarily in same order) whichever completes first and then let the thread sleep for 1-5 seconds which will chosen as randomly.
Here is my Callable Task:
class FactorialCalculator implements Callable{
@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 every time.
Then i compile it through command prompt and then ran it there. Output came different from eclipse but again running multiple times will produce same output here.
Why the output doesn't come randomly?
Thanks in advance.
Update:
Thanks to Ben for pointing out the problem:
Here is the change i made:
Iterator<Future<Integer>> iter = list.iterator();
while(!list.isEmpty()) {
Future<Integer> fi = iter.next();
if(fi.isDone()) {
int temp = fi.get();
System.out.println(temp);
iter.remove();
}
if(!list.isEmpty() && iter.hasNext() == false) {
iter = list.iterator();
}
}