volatile

0 阅读1分钟

作用

  • 可见性

    一个变量声明volatile修饰的变量,将存储在主内存中,而不是线程本地内存, 每一个线程将获取的变量值都是最新的

Image text

  • 有序性(禁止指令重排)

    保证了有序性,限制编译器和处理器的排序

Image text

volatile和synchronized区别

  • volatile

volatile修饰的变量,保持线程的可见性,通常适用一个线程写,多个线程读

  • synchronized

synchronized 用来加锁

volatile是否保证线程安全

  • 不能

volatile修饰的变量,不能保证线程安全和原子性

demo

public class VolatileDemo {

    private static volatile int count = 0;
    public static void main(String[] args) {
        new Thread(() -> {
            while (count == 0) {
                System.out.println("线程" + Thread.currentThread().getName() +"------------------"+ count);
                try {
                    Thread.sleep(TimeUnit.SECONDS.toMillis(5));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("线程" + Thread.currentThread().getName() +"--------end----------"+ count);
        }).start();

        new Thread(() -> {
            try {
                Thread.sleep(TimeUnit.SECONDS.toMillis(20));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            count = 1;
            System.out.println("线程" + Thread.currentThread().getName() +"------------------"+ count);
        }).start();
    }
}


指令重排

提高程序执行效率,重新排序指令,提高执行效率

Image textImage text

  • 三种模式 Image text
  • 如下场景问题,使用volatile解决 Image text