使用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();
        }
    }
相关推荐
qz_Serene8 分钟前
C++:类和对象(上)
开发语言·c++
天疆说26 分钟前
01 硬件选型与 llama.cpp 部署:4× RTX 5880 Ada 跑 DeepSeek-V4-Flash
java·redis·llama
西安景驰电子36 分钟前
《PTP精确时间协议系列》第一篇:从原理到应用,全面解读IEEE 1588
linux·运维·服务器·开发语言·网络·windows·php
ctlover1 小时前
Python文件操作
开发语言·python
luj_17681 小时前
塔防牌:策略与卡牌的智慧碰撞
服务器·c语言·开发语言·经验分享·算法
水无痕simon1 小时前
3 短信应用场景以及平台架构
java·服务器
mister_guo1 小时前
JVM 内存管理原理及生产配置实战:从“参数能启动”到“内存可控”
java·jvm
风流 少年1 小时前
Spring AI 2.0:Tool
java·python·spring
wuyk5551 小时前
3.链表:用指针串联的动态数据结构
c语言·开发语言·数据结构·链表
爱敲键盘的猴子2 小时前
Java Spring -- 声明式事务控制
java·spring·事务控制