Hi I am doing a concurrent programming task in java where I'm using an executorService consisting of 10 threads. I have an array containing 100 elements all set initially to 1000. What I am trying to do is I have 2 indexes from the array, and I need to transfer a random amount from the first index to the second index, my problem is I'm not sure how to use the set function here in this case, as the second parameter of set should be a Future.
var ex = Executors.newFixedThreadPool(10);
List<Future<Integer>> elements = new ArrayList<>();
for (int i = 0; i < 100; i++) {
elements.add(ex.submit(() -> {
int val = 1000;
return val;
}));
}
ex.shutdown();
int sum = 0;
for (Future<Integer> el : elements) {
sum += el.get();
}
System.out.println("Initial sum: " + sum);
for (int i = 0; i < 10_000; i++) {
ex.submit(() -> {
int firstIndex = ThreadLocalRandom.current().nextInt(100);
int secondIndex = ThreadLocalRandom.current().nextInt(100);
int randomAmount = ThreadLocalRandom.current().nextInt(1000);
try {
if (elements.get(firstIndex).get() - randomAmount > 0) {
elements.set(firstIndex,elements.get(firstIndex).get() - randomAmount);
}
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
}