zoukankan      html  css  js  c++  java
  • volatile

    作用

      可见性

      内存屏障(指令重排的屏障)

        注意:不保证原子性

    package com.draymond.three.actomic;
    
    import org.junit.Test;
    
    import java.io.IOException;
    
    /**
     * AtomicInterger 测试
     *
     * @Auther: ZhangSuchao
     * @Date: 2020/3/20 10:27
     */
    public class AtomicIntergerTest {
        private static volatile Integer value = 0; // volatile 可见性,内存屏障(不保证原子性)
    
        /**
         * volatile 测试
         *
         * @throws IOException
         */
        @Test
        public void test1() throws IOException {
    
            Thread thread1 = new Thread(() -> {
                while (true) {
                    System.out.println(value++);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            Thread thread2 = new Thread(() -> {
                while (true) {
                    System.out.println(value++);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
    
            thread1.start();
            thread2.start();
            System.in.read();
        }
    }

    打印的结果有重复的

    说明++操作不保证原子性,如果必须要共享,则需要加上synchorized

  • 相关阅读:
    【javascript】select操作实例
    【javascript】函数
    【javascript】一些资料
    【javascript】操作符:一元操作符
    动态执行Sql
    索引( index )
    事务
    用户相关
    视图(view)
    函数(function)
  • 原文地址:https://www.cnblogs.com/draymond/p/12530269.html
Copyright © 2011-2022 走看看