synchronized修饰的代码不一定具有原子性

56 阅读1分钟

如果执行到中间,执行了wait(),那就失去了原子性

public static void main(String[] args) {
    Object lock = new Object();
    AtomicInteger i = new AtomicInteger();
    new Thread(()->{
        synchronized (lock){
           i.set(1);
            try {
                lock.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if(i.get()==1){
                System.out.println("i==1");
           }
        }
    }).start();
    new Thread(()->{
        synchronized (lock){
            i.set(2);
            lock.notifyAll();
        }
    }).start();
}