首页 > 其他分享 >多线程之countDownlLatch项目使用

多线程之countDownlLatch项目使用

时间:2023-02-05 15:56:30浏览次数:44  
标签:downLatch java String 项目 int get countDownlLatch new 多线程

package com.company;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Main {

    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10,
                300L, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(20000));
        
        // 控制返回的数据按照执行顺序加载打印
        List<Future> futureList = new ArrayList<>();
        int count = 15;
        // 控制线程全部执行完成
        CountDownLatch downLatch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            int finalI = i;
            Future<String> submit = executor.submit(()->get(finalI));
            futureList.add(submit);
            downLatch.countDown();
        }
        // 等待所有线程执行完
        downLatch.await();

        for (Future future : futureList) {
            if (future != null) {
                try {
                    String result = (String) future.get(200L, TimeUnit.MILLISECONDS);
                    System.out.println(result);
                } catch (ExecutionException | TimeoutException e) {
                    // 超时和线程失败策略
                    e.printStackTrace();
                }
            }
        }
        // 项目中不需要此步骤 测试代码需要
        executor.shutdown();
    }

    public static String get(int i) {
        return  i + ",正在执行";
    }
}

标签:downLatch,java,String,项目,int,get,countDownlLatch,new,多线程
From: https://www.cnblogs.com/csh520mjy/p/17093477.html

相关文章