简体   繁体   English

用同步方法和块解决Java线程中的计数器问题

[英]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? 当我在Method上添加sync时,它可以正常工作,但是当我在方法中使用Synchronized块时,它不起作用,为什么? 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. java.lang.Integer不可更改。 When you increment an Integer , you unbox it to a primitive int , increment it, and then autobox the result to a different Integer instance. 当增加一个Integer ,可以将其拆箱为原始int ,然后对其进行递增,然后将结果自动装箱到其他Integer实例。 This means your synchronized block synchronizes on a different object every time, making it pointless - as you've seen yourself. 这意味着您的synchronized块每次都在不同的对象上同步,使其变得毫无意义-正如您所看到的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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