Java并发工具类如ExecutorService使用不当示例
在Java中,ExecutorService
是java.util.concurrent
包中的一个工具类,用于管理和调度线程。以下是一些使用不当的示例:
无休止的提交任务:
ExecutorService executor = Executors.newFixedThreadPool(10);
// 不对的任务提交方式
for (int i = 0; i < 1000; i++) {
Runnable task = () -> System.out.println("Task " + i));
// 不需要立即执行的任务提交,会导致线程池堵塞
executor.submit(task);
}
// 忽略关闭操作
// 等待所有任务完成并关闭后,再释放资源
// executor.shutdown();
无限制添加新线程:
ExecutorService executor = Executors.newFixedThreadPool(10);
// 一次性提交过多的请求,会导致线程池无法处理新任务
List<Runnable> tasks = new ArrayList<>();
for (int i = 0; i < 500; i++) {
tasks.add(() -> System.out.println("Task " + i)));
}
executor.invokeAll(tasks);
// 不需要关闭操作,因为已经提交了所有任务
// executor.shutdown();
错误地取消任务:
ExecutorService executor = Executors.newFixedThreadPool(10);
// 错误地提前取消任务,但任务实际上并未完成
Future<?> future = executor.submit(() -> System.out.println("Task completed after cancellation.")));
// 等待的逻辑错误,应该检查future是否被cancel
try {
future.get(); // 这里会等待任务完成,但实际上任务已经被取消了
} catch (CancellationException ce) {
// 正确地处理任务取消的情况
System.out.println("Task cancelled by ExecutorService.");
}
// 错误地关闭executor,导致未完成的任务被丢弃
// executor.shutdown();
以上示例展示了不当使用
ExecutorService
的一些常见错误。在实际编程中,应遵循好用、高效和资源管理的原则。
还没有评论,来说两句吧...