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

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

猜你喜欢

转载自www.cnblogs.com/q1359720840/p/10668443.html