静态变量加锁失败问题
佛系睡收 2016-10-07 10:55:56 代码示例:
public class TestShareVariables {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(new ShareDemo()).start();
}
//这里加个睡眠时间是为了保证让前面的线程类有足够时间运行好
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(ShareDemo.getCount());
}
}
class ShareDemo implements Runnable {
private static Integer count = 0;
public synchronized static int getCount() {
return count;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (ShareDemo.count) {
count++;
}
//这里加个睡眠时间是为了避免一个线程在获取到时间片时一次就运行完
try {
TimeUnit.MILLISECONDS.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
最后得到的结果不一定都是50
为啥直接对静态变量加锁行不通,而将ShareDemo.count改为ShareDemo.class就没有问题了