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();
}
}