1

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());
    }
}
2787184
  • 3,749
  • 10
  • 47
  • 81

1 Answers1

1

Your threads are executed sequentially:

        s.start();
        try {
            s.join();

you start a thread, you wait until it finished then you start next thread. You should start all threads then wait till all are finished

3gth
  • 550
  • 5
  • 23
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • Even with the below code, my output is still the same.. `public static void main(String[] args) throws InterruptedException { Counter c = new Counter(); SharedCounter1[] array = new SharedCounter1[10]; for(int i=0;i<10;i++) { System.out.println(i+"th thread starting"); array[i]= new SharedCounter1(c); array[i].start(); } for(int i=0;i<10;i++) { array[i].join(); } System.out.println("Final Value::: "+c.getCount()); }` – Shanmuga Priya Oct 06 '17 at 05:58
  • Each of your threads is only incrementing the counter 10 times... what do you think how long this will take? I think this'll be done in almost no time. The time needed for your main thread to start the next one will take much, much, much, much more time! So you should count to much, much, much, much, much higher values to see that effect. – Niklas P Oct 06 '17 at 06:07