zoukankan      html  css  js  c++  java
  • volatile关键字深入理解

    对于java来讲有一个关键字不是很好理解,那就是volatile关键字。

    public class VolatileDemo {
    
        private static volatile int INIT_VALUE = 0;         //使用后效果
    //    private static int INIT_VALUE = 0;                //使用前效果
        private static final int MAXINT = 5;
    
        public static void main(String[] args) {
    
            /**
             * 定义线程一
              */
            Thread tReader = new Thread(()->{
                int localint = INIT_VALUE;
                while(localint < MAXINT){
                    if(localint != INIT_VALUE){
                        Optional.of(Thread.currentThread().getName() + " the value is " + localint).ifPresent(System.out::println);
                        localint = INIT_VALUE;
                    }
                    //Optional.of(Thread.currentThread().getName()+" values is "+ localint +" and " + INIT_VALUE).ifPresent(System.out::println);
                }
            },"thread-reader");
            tReader.start();
    
            Thread tWriter = new Thread(()->{
                int localint = 0;
                while(localint < MAXINT){
                    try {
                        Thread.sleep(100L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Optional.of(Thread.currentThread().getName() + " update the value " + (++localint)).ifPresent(System.out::println);
                    INIT_VALUE = localint;
                }
            },"thread-writer");
            tWriter.start();
    
            System.out.println("the main thread is finished...");
    
        }
    
    }
    

      使用前:

    使用后:

    总结:

    1)保证了不同线程对这个变量进行操作时的可见性,即一个线程修改了某个变量的值,这新值对其他线程来说是立即可见的。

    2)禁止进行指令重排序。

    1、在对变量进行修改的时候,修改自己线程的cup cache的时候,同事刷回主内存;

    2、但是在读取的时候,则不会从新去主内存拿,除非使用volatile进行修饰;

  • 相关阅读:
    App开发Native.js入门指南
    C# Dapper 基本使用 增删改查事务等
    特殊字符码
    assert
    俩个高斯分布之间的KL散度
    np.random.normal(loc=0,scale=1e-2,size=shape)
    解决Github加载ipynb文件缓慢/失败
    画出8个高斯分布散点图
    解决tensorflow报错ValueError: Variable conv1/weights already exists, disallowed.原因:第二次使用的是第一次的就的变量
    互信息
  • 原文地址:https://www.cnblogs.com/linuxone/p/8976191.html
Copyright © 2011-2022 走看看