在学习并发。尝试做一个计数器。 然后不知道为什么有时候计数会多1.有时候又不会。请问要怎样才能完成正确的计数。
public class IncrementTest {
static class Counter {
private AtomicInteger count = new AtomicInteger();
public void increment() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
}
static Counter c = new Counter();
static class Test implements Runnable{
public void run() {
while (c.getCount() < 100){
c.increment();
}
System.out.println(Thread.currentThread().getName() + ":" + c.getCount());
}
}
public static void main(String[] args) {
Test t = new Test();
Thread test = new Thread(t);
test.start();
Test t2 = new Test();
Thread test2 = new Thread(t2);
test2.start();
}
}
修改后的部分
private static AtomicInteger count = new AtomicInteger();
static class Test implements Runnable{
public void run() {
while (count.incrementAndGet() < 10000){}
System.out.println(Thread.currentThread().getName() + ":" + count);
}
}
但是这样子最后一个结果会多1 ....
你同步跟原子性搞混了吧,static class Test implements Runnable{