zoukankan      html  css  js  c++  java
  • volatile 不具有原子性

    volatile 具有可见性,顺序性,但是不具有原子性。

    以一个列子来说明:

    10个线程对 num++ 操作,num++ 是 num=num+1; 不是一个原子操作

    package com.example.demo.thread;
    
    public class VolatileAtomicTest {
        private static int num = 0;
    
        public static void increase(){
            num ++;
        }
    
        public static void main(String[] args) throws InterruptedException {
            Thread[] threads = new Thread[10];
            for (int i = 0; i < threads.length; i++) {
                threads[i] = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int j = 0; j <1000 ; j++) {
                            increase();
                        }
                    }
                });
                threads[i].start();
            }
            for (int i = 0; i < threads.length; i++) {
                threads[i].join();
            }
            System.out.println(num);
        }
    }

    多次运行结果:

    num结果出现不一致,说明volatile不具有原子性

  • 相关阅读:
    vmstat
    linux内存机制
    TOP命令
    linux下查阅文件内容cat,more,less,tail
    linux stat命令
    linux修改主机名-IP
    alias
    linux软硬链接
    linux 常用find命令
    ubuntu下交叉编译imagemagick
  • 原文地址:https://www.cnblogs.com/wanjun-top/p/12831967.html
Copyright © 2011-2022 走看看