多线程之countDownlLatch项目使用
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 + ",正在执行";
}
}
本文来自博客园,作者:土木转行的人才,转载请注明原文链接