Java n 线程更新值

标签 java multithreading java-threads

我正在尝试同时运行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/

相关文章:

java - 当我们拥有currentThread()方法时,为什么Thread类具有静态方法?

java - 具有重写方法的可重入锁?

java - Java中的ScheduledExecutorService和线程

java - SQL Server 中的存储过程需要输出参数作为输入

java - 使用 Spock 在 Spy 对象中 stub 一个 void 方法

java - 使用 maven 安装 microsoft sqljdbc 驱动程序

c# - 启动和停止辅助非 UI 线程

java小程序: which threads invoke lifecycle hooks?

java - 如何从主线程终止子线程

java - 如何将其放入循环中?