Java并发工具库:ExecutorService的详细用法
Java的ExecutorService是处理线程并发的重要工具。它提供了一种方式来管理和调度线程任务。
下面是一些ExecutorService的基本用法:
- 创建ExecutorService实例:
ExecutorService executor = Executors.newFixedThreadPool(5); // 创建固定大小的线程池
- 提交任务到线程池:
Runnable task = () -> {
System.out.println("Task is running by thread.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
executor.submit(task); // 将任务提交给线程池执行
- 关闭ExecutorService:
以上就是ExecutorService的基本用法。在实际项目中,可能会根据需求和场景调整这些用法。// 提交最后一个任务,然后关闭线程池
executor.submit(() -> {
System.out.println("Last task submitted before shutdown.");
executor.shutdown(); // 关闭线程池
try {
if (!executor.isTerminated()) { // 确保线程池已完全终止(可能需要等待)
System.err.println("ExecutorService has not terminated properly.");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}));
还没有评论,来说两句吧...