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());
    }}

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

  • 相关阅读:
    Oracle创建序列,删除序列
    java base58
    百度地图 显示,定位,轮廓图
    百度地图 圈出省份轮廓图并高亮
    基于双向链表的增删改查和排序(C++实现)
    统计字母出现次数
    线程安全
    C++面试秘笈笔记
    牛客选择题刷题
    new delete 浅析
  • 原文地址:https://www.cnblogs.com/q1359720840/p/10668443.html
Copyright © 2011-2022 走看看