package exercise.exercise12;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AtomicityTest implements Runnable {
private int i = 0;
public synchronized int getValue() {
if(i == Integer.MAX_VALUE){
return Integer.MIN_VALUE;
}
return i;
}
private synchronized void evenIncrement() {
i++;
i++;
}
@Override
public void run() {
while (true) {
evenIncrement();
}
}
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
AtomicityTest at = new AtomicityTest();
exec.execute(at);
while (true) {
int value = at.getValue();
if (value % 2 != 0) {
System.out.println(value);
System.exit(0);
}
}
}
}
将getValue方法和evenIncrement方法都加上synchronized关键字,保证i++ 2次没完成的时候,其他线程不会获取到 i 的值。