import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; public class Main { public static void main(String[] args) { int corePoolSize = 5; // 核心线程数 int maxPoolSize = 10; // 最大线程数 long keepAliveTime = 60; // 线程空闲时间 TimeUnit unit = TimeUnit.SECONDS; // 空闲时间单位 BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(10); // 任务队列,这里使用有界队列 ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, unit, workQueue); List<Future<String>> futures = new ArrayList<>(); // 提交任务给线程池 for (int i = 0; i < 10; i++) { final int taskId = i; Future<String> future = executor.submit(() -> { System.out.println("Task-" + taskId + " is running"); try { Thread.sleep(2000); // 模拟任务执行 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Task-" + taskId + " is finished"); return "Task-" + taskId + " result"; // 返回任务结果 }); futures.add(future); } // 获取任务结果 for (Future<String> future : futures) { try { String result = future.get(); // 阻塞直到任务完成并返回结果 System.out.println("Task result: " + result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } executor.shutdown(); } }
标签:Task,int,反悔,future,线程,result,taskId,想得到 From: https://www.cnblogs.com/jiangzishun/p/18182558