Search code examples
javamultithreadingjava-threads

Java n threads updates value


I'm trying to run n threads at the same time. Every thread should sum different array and update the global value.

Unfortunately the global value is updated incorrectly.

I don't want to use thread.join().

This is my code so far:

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);      
}

Any ideas?


Solution

  • If you dont want to use Thread.join you can use 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();
    

    In this case you dont need to use additional synchronization, CountDownLatch is a synchronzier (see java.util.concurrent package description) and according to its javadoc "Until the count reaches zero, actions in a thread prior to calling countDown() happen-before actions following a successful return from a corresponding await() in another thread."