Reputation: 11
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
Reputation: 2221
You can think of count++
as 3 separate steps.
count
count
with the new incremented valueWhen 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
andB
Thread A reads the value of
count
and get1
Thread B reads the value of
count
and get1
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 2Thread B writes the value to
count
count
is now 2 again when it's expected to be 3 after 2 increments
Upvotes: 1