使用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();
        }
    }
相关推荐
Achou.Wang10 小时前
Go语言并发编程中的死锁防范与破解之道
服务器·开发语言·golang
我命由我1234510 小时前
Visual Studio - Visual Studio 注释快捷键
java·c语言·开发语言·c++·ide·java-ee·visual studio
子安柠10 小时前
深入理解 Go 反射:原理、实践与性能陷阱
开发语言·golang
yoyo_zzm10 小时前
ThinkPHP3.X:经典PHP框架的全面解析
开发语言·php
lemon_sjdk10 小时前
DecimalFormat
java·开发语言·python
Nontee11 小时前
一、Java 基础 面试题解答(72题)
java·开发语言
兰令水11 小时前
topcode【随机算法题】【2026.5.16打卡-java版本】
java·数据结构·算法
摇滚侠11 小时前
SpringBoot 面试题 真正的 offer 偏方 Java 基础 Java 高级
java·spring boot·后端
会开花的二叉树11 小时前
Qt信号槽这套机制
开发语言·qt
AI人工智能+电脑小能手11 小时前
【大白话说Java面试题 第58题】【JVM篇】第18题:讲一下三色标记
java·开发语言·jvm