I am learning fork-join technique in java and have written the following program. I am running a for loop (5 times) and I want to run the contents of the for loop in separate threads. This is happening correctly. The problem is that when all the threads are finished, I want a vector of size 5 and it must contain the result of execution of thread 1 at index 0, result of execution of thread 2 at index 1 ............ result of execution of thread 5 at index 4. I am cleanly visualize what I want to achieve but don't know the syntax for it.
Currently I just get 1 number in my vector.
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.*;
public class App {
public static void main(String[] args) {
// TODO Auto-generated method stub
ExecutorService executor = Executors.newCachedThreadPool();
Future<Vector<Integer> > futureResult = null;
for(int i = 0; i < 5; i++){
futureResult = executor.submit(new Callable<Vector<Integer> >(){
@Override
public Vector<Integer> call() throws Exception {
Random random = new Random();
int duration = random.nextInt(4000);
Vector<Integer> v = new Vector<Integer>();
v.add(duration);
return v;
}
});
}
executor.shutdown();
try {
System.out.println(futureResult.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}