多线程遍历for循环(线程池)

本文介绍了一种使用自定义线程池进行并发处理的方法,通过ExecutorService接口创建线程池,采用CountDownLatch来同步线程,实现了对列表中字符串元素的并发处理,并在所有任务完成后关闭线程池。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public List<String> m3( List<String> list) {
        List<String> a=new ArrayList<>();
        //自定义线程池
        ExecutorService pool=new ThreadPoolExecutor(5,10,
                1L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        final CountDownLatch endGate = new CountDownLatch(list.size());
        for (int i = 0; i < list.size(); i++) {
            String str = list.get(i);
            Runnable run = new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);

                        //模拟耗时操作
                        System.out.println("[1]" + Thread.currentThread().getName()+"----"+str);
                        a.add(str);
                    } catch (Exception e) {
                   		 e.printStackTrace();
                    }finally {
                        endGate.countDown();
                    }
                }
            };
            pool.execute(run);
            //pool.submit(run);
        }
       
        try {
            endGate.await();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        pool.shutdown();
        System.out.println("[1] done!");
        return a;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值