I have an object called OBJ which implements Runnable.
It has some members, a constructor, a run() method and a getter for a specific count (one of the members).
In my main method, I have an array of threads, each thread is a new OBJ, and each thread does a certain calculation in the run() method and saves it in the count .
Now, I want to make another loop (in addition to the one where I have started all the threads) and have each thread wait for it to complete and then use the count getter to count all the counts I get from the threads .
How to reach the getter through thread?
Workaround:
Okay, create the OBJ instance before reaching the thread loop:
List objects = new ArrayList();
// Create your objects here
for (int i = 0; i <NUM_OF_OBJ; ++i) {
objects.add(new OBJ());
}
// Run the threads
List threads = new ArrayList();
for (int i = 0; i <NUM_OF_OBJ; ++i) {
Thread t = new Thread(objects.get(i));
threads.add(t);
t.start();
}
// Wait for the threads to finish
for (Thread t : threads) {
t.join();
}
// Sum all counts
int sum = 0;
for (OBJ object : objects) {
sum += object.getCount();
}
Tag:java,multithreading,getter
Source: https://codeday.me/bug/20190621/1250460.html