I am new to Java multithreading. I am learning the concept of race condition.
Based on the Oracle document
http://docs.oracle.com/javase/tutorial/essential/
You are operating on a different object in each thread, thus there is no race condition.So first you need to share the SynchronizedCounter (btw this is a confusing name). Add a counter member in each runnable.
CounterIncThread(SynchronizedCounter counter)
{
this->counter = counter;
}
CounterDecThread(SynchronizedCounter counter)
{
this->counter = counter;
}
...
SynchronizedCounter counter = new SynchronizedCounter();
Thread thread1 = new Thread(new CounterIncThread(counter));
Thread thread2 = new Thread(new CounterDecThread(counter));
Thread thread3 = new Thread(new CounterIncThread(counter));
Also. You are doing only one operation in the runnable. This may not be enough to display the race condition. So loop over a great amount of time.
for(int i = 0; i < 100000; i++) <-- 100000 is just on the top of my head
{
counter.increment();
}
The value will not be the sum of the operation if the race occured,in my case I expect it to be 100000 * 2.
To be even more explicit, run several time. You will likely obtain different values