AtomicInteger 解决JMM原子性问题

public class Test {
public static void main(String[] args) {
MyData myData = new MyData();
for (int i = 0; i < 100; i++) {
new Thread(() ->{
for (int j = 0; j < 100; j++) {
myData.increment();
}
}).start();
}
while (Thread.activeCount() > 2) {
Thread.yield();
}
System.out.println(myData.atomicInteger);

}

}

class MyData {
volatile AtomicInteger atomicInteger = new AtomicInteger(0);
public void increment() {
atomicInteger.incrementAndGet();
}
}

posted @ 2021-08-25 15:38  紫川先生  阅读(49)  评论(0编辑  收藏  举报