使用countDownLatch导致的线程安全问题,线程不安全的List-ArrayList,线程安全的List-CopyOnWriteArrayList

示例代码

java 复制代码
package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class UnSafeCDTest {

    ExecutorService executorService = Executors.newFixedThreadPool(5);

    public static void main(String[] args) throws InterruptedException {
        for(int i = 0; i < 20; i++){
            UnSafeCDTest unSafeCDTest = new UnSafeCDTest();
            unSafeCDTest.test();
        }

    }


    public void test() throws InterruptedException {
        List<String> list = new ArrayList<>();
      //  List<String> list = new CopyOnWriteArrayList<>();
        CountDownLatch countDownLatch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            executorService.submit(() -> {
                // TODO
                list.add("1" );
                // TODO
                // cd
                countDownLatch.countDown();

            });
        }
        countDownLatch.await();
        System.out.println( list.size());

    }
}

输出结果

image.png

可以看到有一个结果为4;

修改ArrayList为线程安全的List,CopyOnWriteArrayList;

验证结果

image.png

CopyOnWriteArrayList为什么是线程安全的

查看源码可以看到通过了加锁实现了线程安全

复制代码
/**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            int len = elements.length;
            Object[] newElements = Arrays.copyOf(elements, len + 1);
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }
相关推荐
Mr_Xuhhh15 分钟前
从理论到实践:深入理解算法的时间与空间复杂度
java·开发语言·算法
望眼欲穿的程序猿21 分钟前
Vscode Clangd 无法索引 C++17 或者以上标准
java·c++·vscode
Lenyiin22 分钟前
《Python 修炼全景指南:一》从环境搭建到第一个程序
开发语言·python
带刺的坐椅31 分钟前
Spring-AI 与 Solon-AI 深度对比分析报告
java·spring·ai·llm·solon·spring-ai·solon-ai
爱码少年39 分钟前
JAVA获取客户端真实IP地址经典写法与Lambda写法对比
java
涛声依旧3931642 分钟前
Python项目实战:学生信息管理系统
开发语言·python·数据挖掘
做个文艺程序员1 小时前
Spring AI + Qwen3.5 实现多步 Agent:从工具调用到自主任务拆解的踩坑全记录
java·人工智能·spring
gentle_ice1 小时前
初入社会的我该何去何从
java
企鹅的蚂蚁1 小时前
【ESP32-S3开发踩坑】C++野指针引发的LoadProhibited死机与CMake依赖锁死排查
开发语言·c++
XiaoQiao6669991 小时前
python 简单题目练手【详解版】【1】
开发语言·python