how do I set up the following thread in Java?
java, multithreading
Solution
I would probably do something like:
public class Main {
int a = 0;
int[] values;
int[] results;
public Main() {
// Init values array
results = new int[N];
}
public int doStuff() {
LinkedList<Thread> threads = new LinkedList<Thread>();
for (final int i : values) {
Thread t = new Thread() {
public void run() {
accumulate(foo(i));
}
};
threads.add(t);
t.start();
}
for (Thread t : threads) {
try {
t.join();
} catch (InterruptedException e) {
// Act accordingly, maybe ignore?
}
}
return a;
}
synchronized void accumulate(int v) {
// Synchronized because a += v is actually
// tmp = a + v;
// a = tmp;
// which can cause a race condition AFAIK
a += v;
}
}
Problem
I have a thread with the following form: each execution of each thread is supposed to run a function in the class. That function is completely safe to run by itself. The function returns a value, say an int. After all threads have been executed, the function values need to be accumulated. So, it goes (in pseudo-code) something like that: ``` a = 0 for each i between 1 to N spawn a thread independently and call the command v = f(i) when thread finishes, do safely: a = a + v end ``` I am not sure how to use Java in that case. The problem is not creating the thread, I know this can be done using ``` new Thread() { public void run() { ... } } ``` the problem is accumulating all the answers. Thanks for any info.