多线程操作公共集合List

声明: 此文章留作自己学习和补充使用

代码

public static void main(String[] args) {

    ExecutorService threadPool = null;
    try {
        // 源集合
        int size = 10000000;
        List<Integer> srcList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            srcList.add(0);
        }

        long time1 = System.currentTimeMillis();
        // 测试多线程设置list集合
        // 1.存在线程安全问题 ArrayList
        //List<Integer> resList = new ArrayList<Integer>(size);
        // 2.线程安全集合 Vector
        //List<Integer> resList = new Vector<Integer>(size);
        // 3.线程安全集合 Collections.synchronizedList
        List<Integer> resList = Collections.synchronizedList(new ArrayList<Integer>(size));
        
        threadPool = Executors.newFixedThreadPool(200);
        // 同步主线程
        CountDownLatch main = new CountDownLatch(size);
        for (Integer integer : srcList) {
            threadPool.execute(() -> {
                resList.add(integer + 1);
                main.countDown();
            });
        }
        // 唤醒主线程
        main.await();

        System.out.println(resList.size());

        long time2 = System.currentTimeMillis();
        System.out.println("耗时: "+(time2 - time1));
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (threadPool != null) {
            threadPool.shutdown();
        }
    }


}

执行结果

  1. 使用ArrayList
9991938
耗时: 5433
  1. 使用Vector
10000000
耗时: 8867
  1. 使用Collections.synchronizedList
10000000
耗时: 7895

说明

预期新集合size为10000000,但使用ArrayList存在线程安全问题,导致size < 10000000
多线程编程时需要操作的的公共List 可以使用Vector或使用 Collections中的synchronized相关方法,其内部的所有方法都是被synchronized修饰的,确保了list 操作的原子性和list对多线程的可见性

synchronizedList和Vector区别

见此文章https://blog.csdn.net/u014754272/article/details/105116400/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值