Java中对线程间的变量访问也需要同步控制
发布时间:2010/8/23 11:02:45 来源:城市学习网 编辑:ziteng
一个简单的计数器,本来以为不需要同步保护,后来发现不行,还是得加上。程序:
public class TestMain {
int i = 0; //计数器初始值为0
public static void main(String[] args) {
TestMain c = new TestMain();
Worker x = new Worker(c);
for (int i=0; i<200; i++) { //200个线程
new Thread(x).start();
}
while (true) { //每隔一秒中输出计数器的值
System.out.println(c.i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
class Worker implements Runnable {
TestMain c;
public Worker(TestMain c) {
this.c = c;
}
public void run() {
try {
Thread.sleep((int)(Math.random() * 25)); //随机Sleep一段时间
} catch (InterruptedException e) {
}
c.i++; //计数器自增 问题在这里 并发写入
}
}
上面的程序50%的几率结果是200,其余的是199,198....
c.i++一句需要并发保护。
本来我以为Java里面++是原子的呢,呵呵。
解决方法,加上同步控制,或者使用JDK5里面新增加的AtomicInteger类。