我正在尝试同时运行n 个线程。每个线程应该对不同的数组求和并更新全局值。
不幸的是,全局值更新不正确。
我不想使用 thread.join()。
这是我到目前为止的代码:
public class myClass {
private static class Values {
private static double sum;
public synchronized static void add(double dd) {
sum += dd;
};
public synchronized double get() {
return sum;
}
}
public static double CreateThreads(double[] array) {
final Values values = new Values();
...
...
...
Thread[] threads = new Thread[nOP];
for (int i = 0; i<threads.length; i++) {
threads[i] = new Thread(new Runnable() {
public void run() {
Values.add(sum(tab));
}
});
threads[i].start();
}
return values.get();
}
public static void main(String[] args) throws IOException {
double[] arr = createArray(4);
double sumLogg = CreateThreads(arr);
System.out.println("\n\nSum: " + sumLogg);
}
有什么想法吗?
最佳答案
如果你不想使用Thread.join,你可以使用CountDountLatch:
CountDownLatch cdl = new CountDownLatch(nOP);
Thread[] threads = new Thread[nOP];
for (int i = 0; i<threads.length; i++) {
threads[i] = new Thread(new Runnable() {
public void run() {
values.add(sum(tab));
cdl.countDown();
}
});
threads[i].start();
}
cdl.await();
在这种情况下,您不需要使用额外的同步,CountDownLatch 是一个同步器(请参阅 java.util.concurrent 包描述),并且根据其 javadoc“直到计数达到零,a 中的操作”调用 countDown() 之前的线程发生在从另一个线程中相应的 wait() 成功返回后的操作之前。”
关于Java n 线程更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53656761/