In: Computer Science
How do you add all the values that return by all the
threads from threadpools?
I have created a threadpool with 1000 of threads and run the task
1000 times. However, when I try to print out the result it gives a
whole bunch of values that return by all the threads, it looks
like...
Thread-1 xxxx
Thread-2 xxxx
Thread-3 xxxx
Thread-4 xxxx
.
.
.
.
.
Is there a possible way to get a single value back instead of whole bunch of value? Taking the average value of all the threads are fine as well.
This question is based on Java only. Thank you!!
I believe what you are looking for is "atomic Object" to hold values from all the Threads in a single variable.
In Java for concurrent execution we have java.util.concurrent.atomic package
a reference to the same can be find here
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html
Example: you have 1000 threads and each thread is doing "task" 1000 times. You want to keep a counter of how many times task was executed in total.
Solution : Each time the task is executed by any thread we will increment atomicInteger variable.
/*****Sample Code********/
AtomicInteger counter = new AtomicInteger(0); //Declaring the atomic integer variable
counter.incrementAndGet() //do this each time task is executed.
/*************Sample Code********/
Moreover you can create your atomic variable static so that it is shared between all the object of the class and there remains only a single instance of atomic variable.
In case you need more help on this, Comment :) Happy to help.