public class PrintABVolatile implements IPrintAB {
private static final int MAX_PRINT_NUM = 100;
private static volatile int count = 0;
@Override
public void printAB() {
new Thread(() -> {
while (count < MAX_PRINT_NUM) {
if (count % 2 == 0) {
log.info("num:" + count);
count++;
}
}
}).start();
new Thread(() -> {
while (count < MAX_PRINT_NUM) {
if (count % 2 == 1) {
log.info("num:" + count);
count++;
}
}
}).start();
}
}
请问这样能保证线程安全吗..感觉volatile不能保证啊 i++不是原子的
incrementAndGet()底层是CAS操作,调用的是Unsafe类,线程安全