为什么这里的number不用volatile也能保证可见性

Winson
  • 6
class ShareData {
    private int number=0;
    private Lock lock=new ReentrantLock();
    private Condition condition=lock.newCondition();

    public void sub() {
        lock.lock();
            try {
                while(number==0){
                    condition.await();
                }
                number--;
                System.out.println(Thread.currentThread().getName()+"\t"+number);
                condition.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
    }
    public void add(){
        lock.lock();
        try {
            while(number!=0){
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
/**
 * 初始值为零的变量,两个线程对其交替操作,一个加1,一个减一,来5轮
 */
public class ProdConsumer_TraditionDemo {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                shareData.add();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                shareData.sub();
            }
        },"B").start();
    }

}
回复
阅读 2k
2 个回答
✓ 已被采纳

因为有锁 (lock.lock()

换而言之,就是因为有锁读到的数据一定是最新的,同步方法压栈,操作数栈中的值肯定是最新的。

宣传栏