Documentation

The Java™ Tutorials
Hide TOC
Thread Pools线程池
Trail: Essential Java Classes
Lesson: Concurrency
Section: High Level Concurrency Objects
Subsection: Executors

Thread Pools线程池

Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads. java.util.concurrent中的大多数执行器实现都使用线程池,线程池由工作线程组成。This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks.这种线程与它执行的RunnableCallable任务分开存在,通常用于执行多个任务。

Using worker threads minimizes the overhead due to thread creation. 使用工作线程可以最大限度地减少由于创建线程而产生的开销。Thread objects use a significant amount of memory, and in a large-scale application, allocating and deallocating many thread objects creates a significant memory management overhead.线程对象使用大量内存,在大型应用程序中,分配和取消分配许多线程对象会产生大量内存管理开销。

One common type of thread pool is the fixed thread pool. 一种常见的线程池类型是固定线程池This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread. 这种类型的池总是有指定数量的线程在运行;如果线程在仍在使用时以某种方式终止,它将自动替换为新线程。Tasks are submitted to the pool via an internal queue, which holds extra tasks whenever there are more active tasks than threads.任务通过内部队列提交到池中,当活动任务多于线程时,内部队列会保存额外的任务。

An important advantage of the fixed thread pool is that applications using it degrade gracefully. 固定线程池的一个重要优点是,使用它的应用程序可以正常降级To understand this, consider a web server application where each HTTP request is handled by a separate thread. 为了理解这一点,考虑一个Web服务器应用程序,其中每个HTTP请求由一个单独的线程处理。If the application simply creates a new thread for every new HTTP request, and the system receives more requests than it can handle immediately, the application will suddenly stop responding to all requests when the overhead of all those threads exceed the capacity of the system. 如果应用程序只是为每个新HTTP请求创建一个新线程,并且系统接收到的请求超过了它可以立即处理的数量,那么当所有这些线程的开销超过系统的容量时,应用程序将突然停止响应所有请求。With a limit on the number of the threads that can be created, the application will not be servicing HTTP requests as quickly as they come in, but it will be servicing them as quickly as the system can sustain.由于可以创建的线程数量有限,应用程序将不会在HTTP请求传入时尽快为其提供服务,但会在系统能够支持时尽快为其提供服务。

A simple way to create an executor that uses a fixed thread pool is to invoke the newFixedThreadPool factory method in java.util.concurrent.Executors. 创建使用固定线程池的执行器的简单方法是调用java.util.concurrent.Executors中的newFixedThreadPool工厂方法。This class also provides the following factory methods:此类还提供以下工厂方法:

If none of the executors provided by the above factory methods meet your needs, constructing instances of java.util.concurrent.ThreadPoolExecutor or java.util.concurrent.ScheduledThreadPoolExecutor will give you additional options.如果上述工厂方法提供的执行器都不满足您的需要,那么构建java.util.concurrent.ThreadPoolExecutorjava.util.concurrent.ScheduledThreadPoolExecutor的实例将为您提供其他选项。


Previous page: Executor Interfaces
Next page: Fork/Join