zoukankan      html  css  js  c++  java
  • 并发编程-多线程共享变量不安全

    最近开始研究并发的问题,今天找了段代码,是在并发环境共享变量的不安全问题,如下所示:

    public class ConcurrentTest {
        //1000个请求
        private static int quest_count = 1000;
        //同时允许50个请求运行
        private static int concurrent_count = 50;
    
        private static int count = 0;
        public static void main(String[] args) throws Exception{
            ExecutorService executor = Executors.newCachedThreadPool();
            final Semaphore semaphore = new Semaphore(concurrent_count);//信号量
            final CountDownLatch countDownLatch = new CountDownLatch(quest_count);//
    
            for (int i = 0; i < quest_count; i++){
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            semaphore.acquire();
                            add();
                            semaphore.release();
                            countDownLatch.countDown();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
              
            }
            countDownLatch.await();
            executor.shutdown();
            System.out.printf("count:"+count);
        }
    
        private static void add(){
            count++;
        }
    }

    我创建了一个线程池,是cachedThreadPool,最大支持Integer.MAX_VALUE个线程,具体实现代码如下:

    public static ExecutorService newCachedThreadPool() {
            return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                          60L, TimeUnit.SECONDS,
                                          new SynchronousQueue<Runnable>());
        }

    之后再详细说线程池。继续上面的代码,我在主线程中通过for循环创建了1000个请求,最多同时允许50个线程运行,每个线程做累加操作,最后打印count结果。

    结果如下所示:count:947、count:938、count:876  结果都不是1000,显而易见的。

    原因分析:A线程从主内存中获取到变量count放置在自己线程私有线程栈中,对count做+1操作  count =1,B线程同时从主存中获取count(count=0)放置在线程B的栈中,对count做+1操作,之后B和A如果都将count写回主存,count还是1,我们期望值应该是2。另外++操作在cpu中会拆成三条指令,取值、自增、赋值,并不是原子的,也会有风险。

    改造:

    方案1:使用AtomicInteger

    代码如下:

    public class ConcurrentTest {
        //1000个请求
        private static int quest_count = 1000;
        //同时允许50个请求运行
        private static int concurrent_count = 50;
    
        private static AtomicInteger count = new AtomicInteger(0);
    
        public static void main(String[] args) throws Exception{
            ExecutorService executor = Executors.newCachedThreadPool();
            final Semaphore semaphore = new Semaphore(concurrent_count);//信号量
            final CountDownLatch countDownLatch = new CountDownLatch(quest_count);//
    
            for (int i = 0; i < quest_count; i++){
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            semaphore.acquire();
                            add();
                            semaphore.release();
                            countDownLatch.countDown();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            countDownLatch.await();
            executor.shutdown();
            System.out.printf("count:"+count);
        }
    
        private static void add(){
            count.incrementAndGet();
        }
    }

    执行结果:count:1000

    下一篇文章分析AtomicInteger为什么在多线程下共享变量安全。

    欢迎关注Java流水账公众号
  • 相关阅读:
    搭建web攻防环境
    远程控制
    网络攻击
    论文翻译:《PRIMES is in P》——素性测试的确定性多项式时间算法研究
    从Fouier级数到DCT
    同态加密简要概述
    杂谈:探究副词“有点”用于修饰形容词和动词的使用范围
    题解:洛谷P2055/[ZJOI2009] 假期的宿舍(匈牙利算法)
    笔记:二部图最大匹配的匈牙利算法
    杂谈:AI Intro课程作业——卷积神经网络练练手之MNIST数据集
  • 原文地址:https://www.cnblogs.com/guofu-angela/p/9363635.html
Copyright © 2011-2022 走看看