-1

Here I am using synchronized for common counter variable for both threads t1, t2 but even though counter value getting as inconsistency, please can any one explain why it's giving results like this and give a solution.

public class Sync {
    public static int counter = 0;

    private static synchronized void increment() {
        ++counter;
    }

    public static void process() {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++)
                    increment();
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++)
                    increment();
            }

        });
        t1.start();
        t2.start();


    }

    public static void main(String[] args) {
        process();
        System.out.println("counter is:: " + counter);
    }
}

It should give counter value as 2000.

Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28
  • 1
    You start your threads, but you do not wait for them to complete. If you want to see 2000, then you should call join on both threads – bogertron Jul 24 '19 at 18:51
  • 1
    The call to `process()` does not wait for the threads to complete. Hence, the println will not necessarily give you the final couter value. – Michael Roland Jul 24 '19 at 18:52

1 Answers1

3

Because your Main thread does not wait for the other threads to finish. And it prints the result while other threads are still incrementing the counter.

Use Thread.join() to fix it:

t1.join();
t2.join();
Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28