zoukankan      html  css  js  c++  java
  • volatile不能保证数据完整性的小案例

    package juc;
    
    import java.util.Collections;
    import java.util.HashSet;
    import java.util.Set;
    
    public class AtomicIntegerTest {
        private  static volatile  int value=0;
       private static Set set= Collections.synchronizedSet(new HashSet<Integer>());
    
        public static void main(String[] args) throws InterruptedException {
            Thread  t1 =new Thread(){
                            @Override
                            public void run() {
                                //
                                int x=0;
    
                                while(x<500){
                                    int tmp=value;
                                    set.add(value);
                                    System.out.println(Thread.currentThread().getName()+":"+tmp);
                                    value+=1;
                                    x++;
                                }
    
    
    
                        }
        };
     Thread  t3 =new Thread(){
                            @Override
                            public void run() {
                                //
                                int x=0;
    
                                while(x<500){
                                    int tmp=value;
                                    set.add(value);
                                    System.out.println(Thread.currentThread().getName()+":"+tmp);
                                    value+=1;
                                    x++;
                                }
    
    
    
                        }
        };
    
    
            Thread  t2 =new Thread(){
                @Override
                public void run() {
                    //
    
    
                    int x=0;
                    while(x<500){
                        set.add(value);
                        int tmp=value;
                        System.out.println(Thread.currentThread().getName()+":"+tmp);
                        value+=1;
                        x++;
                    }
    
    
    
                }
            };
            t1.start();
            t2.start();
            t3.start();
            t1.join();
            t2.join();
            t3.join();
            System.out.println(set.size());
    }}

    打印结果少值,并不是真正打印出足够个数,有重复数据或丢失。

  • 相关阅读:
    表优化
    存储和压缩
    自定义函数
    Hadoop中SecondaryNameNode和HA(高可用)区别
    ASUS笔记本,更换了固态硬盘,重装系统前后开机都自动进入BIOS界面
    顶部下拉菜单制作笔记
    综合笔记
    工具sublime安装
    head引入样式
    滚动固定导航代码
  • 原文地址:https://www.cnblogs.com/q1359720840/p/10668443.html
Copyright © 2011-2022 走看看