LeticiaS
LeticiaS

Reputation: 11

I don't get how threads work in this case

The following code is shows how no race condition in thread works, but I don't get the difference between with the synchronized and without it. I thought the static variable counter will be added to 20000 anyway but it turned out that without synchronized counter would be less than 20000. Can you please explain how threads work in this case? Also, in Java, are threads are actually not running "concurrently", instead are they taking turns to run for a while?

public class NoRaceCondition implements Runnable {
    private static int counter = 0;
    private static Object gateKeeper = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(new NoRaceCondition());
        Thread t2 = new Thread(new NoRaceCondition());
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) { e.printStackTrace(); }
        System.out.printf("counter = %d\n", counter);
    }

    public void run() {
        synchronized (gateKeeper) {
            for (int i = 0; i < 10000; i++) {
                {
                    counter++;
                }
            }
        }
    }
}

Upvotes: 0

Views: 74

Answers (1)

tanyehzheng
tanyehzheng

Reputation: 2221

You can think of count++ as 3 separate steps.

  1. read the value of count
  2. increment the value
  3. override count with the new incremented value

When multiple thread execute the above steps concurrently, race conditions may occur. 1 example of race condition is

Let count = 1

Let there be 2 threads named A and B

Thread A reads the value of count and get 1

Thread B reads the value of count and get 1

Thread A increments its value and get 2

Thread B increments its value and get 2

Thread A writes the value to count

count is now 2

Thread B writes the value to count

count is now 2 again when it's expected to be 3 after 2 increments

Upvotes: 1

Related Questions