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 + ",正在执行";
}
}
多线程之countDownlLatch项目使用
最新推荐文章于 2024-11-07 13:06:59 发布