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

  • 相关阅读:
    GUI 之 JDialog弹窗
    GUI Swing 之 JFrame窗体
    GUI 键盘监听事件
    GUI 窗口监听事件
    GUI 鼠标监听事件,模拟画图工具
    shell编程
    Ubuntu20.04 Linux初识
    rlwrap的使用
    5个相见恨晚的Linux命令,每一个都非常实用
    Bash初识与常用命令
  • 原文地址:https://www.cnblogs.com/draymond/p/12530269.html
Copyright © 2011-2022 走看看