public class Vs {
public static int count = 0;
public synchronized static void inc() {
//这里延迟1毫秒,使得结果明显
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
count++;
}
public static void main(String[] args) {
//同时启动1000个线程,去进行i++计算,看看实际结果
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
Vs.inc();
}
}).start();
}
System.out.println("运行结果:Counter.count=" + Vs.count);
}
}
问题:为什么Synchronized没能将方法锁住。
加了Synchronized后得出的结果大概是一百多
去掉Synchronized后的结果大概是九百多
为什么会有这样的差异?