import java.util.concurrent.*;
import java.util.*;
class MyRunnable implements Runnable {
Queue<Integer> queue;
MyRunnable(Queue<Integer> queue) {
this.queue = queue;
}
public void run() {
// simulate some kind of result being returned
int randomNum = ThreadLocalRandom.current().nextInt(0, 200);
queue.add(randomNum);
}
}
class Main {
public static void main(String[] args) throws InterruptedException {
int threadCount = 10;
Queue<Integer> queue = new ConcurrentLinkedQueue<Integer>();
Thread[] n = new Thread[threadCount];
for (int i = 0; i < threadCount; i++) {
n[i] = new Thread(new MyRunnable(queue));
n[i].start();
}
for (int i = 0; i < threadCount; i++) {
n[i].join();
}
int avg = queue
.stream()
.reduce(0, (acc, e) -> acc + e / queue.size());
System.out.println(avg);
}
}
To embed this program on your website, copy the following code and paste it into your website's HTML: