加锁机制既可以确保可见性又可以确保原子性,而volatile变量只能确保可见性。

public class NoVisibility {
    private static boolean ready;
    private static int number;
    
    private static class ReaderThread extends Thread{
        public void run(){
            while(!ready){
                Thread.yield();
            }
            System.out.println(number);
        }
    }
    
    public static void main(String[] args){
        new ReaderThread().start();
        number = 45;
        ready = true;
    }
}

(1)Novisibility可能会持续循环,因为ReaderThread可能会看不到写入ready的值。

(2)NoVisibility可能会输出0,因为ReaderThread可能会看到写入ready的值,却没有看到写入number的值。--重排序(在没有同步的情况下,编译器、

处理器、运行时都可能对操作的执行顺序进行调整)

 

使用volatile的情况:

(1)对变量的写入操作不依赖变量的当前值,或确保只有单个线程更新变量的值。

(2)在访问变量时不需要加锁

 

相关文章:

  • 2022-12-23
  • 2022-02-24
  • 2022-12-23
  • 2022-12-23
  • 2021-09-23
  • 2021-10-14
  • 2021-05-12
  • 2022-12-23
猜你喜欢
  • 2022-02-06
  • 2021-09-30
  • 2022-01-14
  • 2021-06-13
  • 2022-02-23
相关资源
相似解决方案