为什么以下多线程代码不起作用?我相信答案应该是 20000



为什么同步增量方法时我没有得到 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);
    }
}

JLS 对于synchronized方法,明确指出以下内容:

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

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

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

相关内容

最新更新