我有一个具有以下形式的线程:
每个线程的每次执行都应该运行类中的一个函数。该功能可以完全安全地自行运行。该函数返回一个值,比如一个 int。
所有线程执行完毕后,需要累加函数值。
所以,它(在伪代码中)是这样的:
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
我不确定在那种情况下如何使用 Java。
问题不在于创建线程,我知道这可以使用
new Thread() {
public void run() {
...
}
}
问题是累积所有的答案。
感谢您提供任何信息。
最佳答案
我可能会这样做:
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;
}
}
关于java - 如何在 Java 中设置以下线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12521739/