欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 艺术 > 使用countDownLatch导致的线程安全问题,线程不安全的List-ArrayList,线程安全的List-CopyOnWriteArrayList

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

2025/5/15 5:17:50 来源:https://blog.csdn.net/weixin_47267435/article/details/147844651  浏览:    关键词:使用countDownLatch导致的线程安全问题,线程不安全的List-ArrayList,线程安全的List-CopyOnWriteArrayList

示例代码

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(() -> {// TODOlist.add("1" );// TODO// cdcountDownLatch.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();}}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词