繁体   English   中英

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

[英]Solving Counter Problem in Java Thread With synchronized method and block

我只是在线程中针对计数器问题编写了代码。 当我在Method上添加sync时,它可以正常工作,但是当我在方法中使用Synchronized块时,它不起作用,为什么? 我想我缺少了一些东西。

    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不可更改。 当增加一个Integer ,可以将其拆箱为原始int ,然后对其进行递增,然后将结果自动装箱到其他Integer实例。 这意味着您的synchronized块每次都在不同的对象上同步,使其变得毫无意义-正如您所看到的那样。

暂无
暂无

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

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