【问题标题】:Why the following code of multithreading is not working? The answer should be 20000 I believe为什么下面的多线程代码不起作用?答案应该是 20000 我相信
【发布时间】:2016-02-20 23:59:41
【问题描述】:

为什么我在增量方法同步时没有得到 20000。我对 runnable 做了同样的事情,而且效果很好。

   public class ThreadClass extends Thread
    {
            static int count=0;
            public synchronized void increment()
            {
                count++;
            }

    public void run()
    {
        for(int i=0;i<10000;i++)
        {
            increment();
        }
    }; 

}

public class Main {

    public static void main(String[] args) {

        ThreadClass t1=new ThreadClass();
        ThreadClass t2= new ThreadClass();

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

        try {
            t2.join();
            t1.join();
            } 
        catch (Exception e) 
            {
            e.printStackTrace();
            }
        System.out.println(ThreadClass.count);
    }

}

【问题讨论】:

    标签: java multithreading synchronization


    【解决方案1】:

    JLS,对于synchronized 方法,clearly states 如下:

    对于实例方法,使用与 this(调用该方法的对象)关联的监视器。

    因此,两个ThreadClass 实例将独立锁定,不会有共同的锁来保护对count 的错误写入。

    在Threadclass.class 上显式同步或将increment() 设为静态,以使写入安全的方式实际同步。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-14
      • 2017-06-15
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      • 2016-03-21
      • 1970-01-01
      • 2018-12-15
      相关资源
      最近更新 更多