import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class ThreadPoolAllDoneCheck {
public static void main(String[] args) {
// 创建固定大小线程池
ExecutorService executor = Executors.newFixedThreadPool(5);
// 存放 Future 结果
List<Future<Boolean>> futures = new ArrayList<>();
try {
// 提交多个任务
for (int i = 0; i < 10; i++) {
futures.add(executor.submit(() -> yourTask()));
}
// 等所有线程执行完成后,再统一判断结果
boolean hasFalse = false;
for (Future<Boolean> future : futures) {
try {
Boolean result = future.get(); // 阻塞直到任务完成
if (!result) {
hasFalse = true;
}
} catch (ExecutionException e) {
// 捕获任务内部抛出的异常
e.printStackTrace();
hasFalse = true; // 认为失败
}
}
// 所有线程都完成后再判断
if (hasFalse) {
throw new RuntimeException("存在任务执行结果为 false!");
}
System.out.println("全部任务执行成功!");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
// 模拟你的业务方法
public static boolean yourTask() throws InterruptedException {
Thread.sleep(500); // 模拟耗时
boolean result = Math.random() > 0.2; // 80% 概率返回 true
System.out.println(Thread.currentThread().getName() + " 执行任务,结果: " + result);
return result;
}
}
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0
许可协议。转载请注明来自Youzi !
评论
评论