public class VolatileExample {
private volatile int count = 0;
public void increase() {
count++;
}
public int getCount() {
return count;
}
public static void main(String[] args) {
final VolatileExample example = new VolatileExample();
for (int i = 0; i < 10; i++) {
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
example.increase();
}
}).start();
}
// 等待所有线程执行完毕
while (Thread.activeCount() > 2) {
Thread.yield();
}
System.out.println("Count: " + example.getCount());
}
}