import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
List<Callable<String>> taskList = new ArrayList<>();
taskList.add(new Task("Task 1"));
taskList.add(new Task("Task 2"));
taskList.add(new Task("Task 3"));
//... add more tasks
try {
List<Future<String>> futures = executorService.invokeAll(taskList);
for (Future<String> future : futures) {
System.out.println(future.get());
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
static class Task implements Callable<String> {
private final String name;
public Task(String name) {
this.name = name;
}
@Override
public String call() throws Exception {
// 在此处执行任务的逻辑
System.out.println("Executing task: " + name);
Thread.sleep(1000); // 模拟耗时操作
if (Math.random() > 0.5) { // 有50%的几率任务成功
System.out.println("Task " + name + " is successful");
return name + " is successful"; // 成功返回的结果
} else {
throw new RuntimeException("Task " + name + " failed"); // 失败抛出异常
}
}
}
}
标签:Task,name,add,taskList,并发,任务,任一,new,String
From: https://www.cnblogs.com/ArthurHenry/p/17749533.html