为什么同步增量方法时我没有得到 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()
静态,以便以安全写入的方式实际同步。