Ankit Bansal
Ankit Bansal

Reputation: 2348

Java multi threading when multiple threads updating same variable

This is the program

public class Thread2 implements Runnable {

    private static int runTill = 10000;
    private static int count = 0;
    @Override
    public void run() {
        for(int i=0;i<runTill;i++) {
            count++;
        }
    }
    
    public static void main(String s[]) {
        int iteration = 10;
        for(int i = 0; i < iteration ;i++) {
            Thread t = new Thread(new Thread2());
            t.start();
        }
        
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        System.out.println("Expected : "+(iteration * runTill));
        System.out.println("Actual : "+count);
    }

}

At the end I want count to be equal to (Expected : 100000). How can I achieve this?

Upvotes: 0

Views: 520

Answers (3)

tevemadar
tevemadar

Reputation: 13195

As the comments suggest, besides the need for synchronizing access (to count, became an AtomicInteger here), threads should be waited to complete using Thread.join(), instead of "guessing" their runtime:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Thread2 implements Runnable {

    private static int runTill = 10000;
    private static AtomicInteger count = new AtomicInteger();

    @Override
    public void run() {
        for (int i = 0; i < runTill; i++) {
            count.incrementAndGet();
        }
    }

    public static void main(String s[]) {
        int iteration = 10;
        List<Thread> threads = new ArrayList<Thread>();
        for (int i = 0; i < iteration; i++) {
            Thread t = new Thread(new Thread2());
            threads.add(t);
            t.start();
        }

        try {
            for (Thread t : threads)
                t.join();
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }

        System.out.println("Expected : " + (iteration * runTill));
        System.out.println("Actual : " + count);
    }
}

Upvotes: 0

Angel Koh
Angel Koh

Reputation: 13495

use "compare and set" instead of "increment and get"

private static AtomicInteger count = new AtomicInteger();

@Override
public void run() {
    for(int i=0;i<runTill;i++) {

        //note: another thread might reach this point at the same time when i is 9,999
        // (especially if you have other codes running prior to the increment within the for loop)
        // then count will be added 2x if you use incrementAndGet
        boolean isSuccessful = count.compareAndSet(i, i+1);

        if(!isSuccessful) 
            System.out.println("number is not increased (another thread already updated i)");
    }
}

Upvotes: 0

M A
M A

Reputation: 72844

A call to count++ is not atomic: it first has to load count, increment it and then store the new value in the variable. Without synchronization in place, threads will interleave during execution of this operation.

A simple way to get what you want is to use an AtomicInteger:

private static AtomicInteger count = new AtomicInteger();

@Override
public void run() {
    for(int i=0;i<runTill;i++) {
        count.incrementAndGet();
    }
}

Upvotes: 2

Related Questions