并发编程-多线程共享变量不安全

本文探讨了在并发环境中共享变量出现的安全问题,并通过实例演示了如何使用AtomicInteger解决这一问题,确保多线程环境下的变量操作安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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为什么在多线程下共享变量安全。

转载于:https://www.cnblogs.com/zhengwangzw/p/9363635.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值