简体   繁体   中英

Solving Counter Problem in Java Thread With synchronized method and block

I just wrote code for counter problem in a thread. When I add synchronized on Method its working fine but when I use synchronized block inside a method it does not work, why? Something I am missing, I guess.

    public class CounterProblem {
    class Counter implements Runnable {
        private Integer count = 0;

        @Override
        public void run() {
            for(int i = 0; i < 10000; i++) {
                increment();
            }
        }
//      THIS GIVES 20000 which is correct every time.
        public synchronized void increment() {
            count++;
        }
//      THIS GIVES wrong every time. WHY ?
//      public void increment() {
//          synchronized(count) {
//              count++;
//          }
//      }
    }
    public static void main(String[] args) throws InterruptedException {
        CounterProblem counterProblem = new CounterProblem();
        Counter counter = counterProblem.new Counter();
        Thread thread1 = new Thread(counter);
        Thread thread2 = new Thread(counter);
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println(counter.count);
    }
}

java.lang.Integer 's aren't mutable. When you increment an Integer , you unbox it to a primitive int , increment it, and then autobox the result to a different Integer instance. This means your synchronized block synchronizes on a different object every time, making it pointless - as you've seen yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM