Java 线程池大小(Executors) [英] Java thread pool size (Executors)

查看:68
本文介绍了Java 线程池大小(Executors)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有 3 个线程的应用程序,我将把它切换到由 ScheduledExecutorService 管理.创建此实例时,您必须指定线程池大小,但这是什么?这是否意味着如果我计划运行 3 个任务,我应该为每个任务创建一个大小为 3 个的线程池?

I have an application that has 3 threads which I'm going to switch over to be managed by ScheduledExecutorService. When creating an instance of this you must specific the thread pool size but what is this? Does this mean if I'm planning on running 3 tasks I should create a thread pool size of 3 one for each?

推荐答案

假设您已经像这样创建了 ScheduledExecutorService

Assuming You have created ScheduledExecutorService like this

ScheduledExecutorService executorService = Executors.newFixedThreadPool(10);

executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Asynchronous task");
    }
});

executorService.shutdown();

现在这里发生了什么:

  • 首先使用 newFixedThreadPool() 创建一个 ExecutorService工厂方法.这将创建一个带有 10 个线程的线程池执行任务.
  • 其次,Runnable 接口的匿名实现是传递给 execute() 方法.这会导致 Runnable 成为由 ExecutorService 中的一个线程执行.
  • First an ExecutorService is created using the newFixedThreadPool() factory method. This creates a thread pool with 10 threads executing tasks.
  • Second, an anonymous implementation of the Runnable interface is passed to the execute() method. This causes the Runnable to be executed by one of the threads in the ExecutorService.

线程池管理工作线程池.线程池 包含一个工作队列,其中包含等待执行的任务.

Thread pools manage a pool of worker threads. The thread pools contains a work queue which holds tasks waiting to get executed.

现在来:

这是否意味着如果我计划运行 3 个任务,我应该创建一个线程池大小为 3 一个?

Does this mean if I'm planning on running 3 tasks I should create a thread pool size of 3 one for each?

是的,以便可以并行执行所有 3 个任务.

Yes so that all 3 task can be executed parallely .

现在这是一篇关于我们的线程池应该有多大的好文章?

这篇关于Java 线程池大小(Executors)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆