我有一个有 3 个线程的应用程序,我将其切换为由 ScheduledExecutorService 管理。创建此实例时,您必须指定线程池大小,但这是什么?这是否意味着如果我计划运行 3 个任务,我应该为每个任务创建一个大小为 3 的线程池?
最佳答案
假设您已经像这样创建了 ScheduledExecutorService
ScheduledExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
}
});
executorService.shutdown();
现在这里发生了什么:
- 首先使用
newFixedThreadPool() 创建 ExecutorService
工厂方法。这将创建一个具有10 个线程
的线程池 执行任务。 - 其次,Runnable接口(interface)的匿名实现是 传递给execute()方法。这会导致 Runnable 成为 由 ExecutorService 中的线程之一执行。
Thread pools manage a pool of worker threads. The
thread pools
contains a work queue which holds tasks waiting to get executed.
现在来到:
Does this mean if I'm planning on running 3 tasks I should create a thread pool size of 3 one for each?
是的,这样所有 3 个任务就可以并行执行。
现在这是一篇关于 How big should our thread pool be? 的好文章
关于Java线程池大小(执行器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28431293/