I am trying to understand thread synchronization. I have implemented a counter whose initial value is 0. 10 threads each increment the counter 10 times. I guess the output of the following code must be something that is not 100, since I have not synchronized it. But I am always getting my final count as 100 only whether or not I synchronize the incrementCount method inside Counter.java. Can somebody please explain how can I see the wrong outputs because of not synchronizing ?
package practise.java;
public class Counter {
private int count = 0;
public int getCount()
{
return count;
}
public void incrementCount()
{
count++;
}
}
package practise.java;
public class SharedCounter1 extends Thread{
Counter counter;
public SharedCounter1(Counter c)
{
counter = c;
}
@Override
public void run() {
for(int i = 0;i<10;i++)
{
//System.out.println(this.getName() + "previous count :: "+counter.getCount());
counter.incrementCount();
//System.out.println("after incrementing ::: "+counter.getCount());
}
}
public static void main(String[] args)
{
Counter c = new Counter();
for(int i=0;i<10;i++)
{
System.out.println(i+"th thread starting");
SharedCounter1 s= new SharedCounter1(c);
s.start();try {
s.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Final Value::: "+c.getCount());
}
}