Java中的线程池有什么用?

时间:2021-01-21 21:02:11

What is the use of a Thread pool? Is there a good real world example?

线程池有什么用?有一个很好的现实世界的例子吗?

6 个解决方案

#1


39  

A thread pool is a group of threads initially created that waits for jobs and executes them. The idea is to have the threads always existing, so that we won't have to pay overhead time for creating them every time. They are appropriate when we know there's a stream of jobs to process, even though there could be some time when there are no jobs.

线程池是最初创建的一组线程,它们等待作业并执行它们。我们的想法是让线程始终存在,这样我们就不必每次都花费很多时间来创建它们。当我们知道要处理的工作流时,它们是合适的,即使可能有一段时间没有工作。

Here's a nice diagram from Wikipedia: Java中的线程池有什么用?

这是*的一张很好的图表:

#2


6  

Thread Pools from the Java Tutorials has a good overview:

Java教程中的线程池有一个很好的概述:

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.

使用工作线程可以最大限度地减少线程创建带来的开销线程对象使用大量内存,在大型应用程序中,分配和释放许多线程对象会产生大量的内存管理开销。

#3


5  

Thread Pools are useful only in a Server-client kind of situation where the number/occurrence of client requests cannot be determined/predicted.

线程池仅在服务器 - 客户端类型的情况下有用,其中无法确定/预测客户端请求的数量/发生。

In this scenario, creating a new Thread each time a client request is made has two dis-advantages:

在这种情况下,每次发出客户端请求时创建一个新线程有两个不利之处:

1) Run time latency for thread creation: Creation of a thread requires some time, thus the actual job does not start as soon as the request comes in. The client may notice a slight delay.

1)线程创建的运行时延迟:创建线程需要一些时间,因此实际作业不会在请求进入后立即启动。客户端可能会注意到稍有延迟。

This criteria is crucial in interactive systems, where the client expects an immediate action.

此标准在交互式系统中至关重要,客户希望立即采取行动。

2) Uncontrolled use of System Resources: Threads consume system resources (memory etc.), thus the system may run out of resources in case there is an unprecedented flow of client requests.

2)系统资源的不受控制的使用:线程消耗系统资源(存储器等),因此在存在前所未有的客户端请求流的情况下,系统可能耗尽资源。

Thread pools address the above concerns by:
1) Creating specified number of threads on server start-up instead of creating them during the run-time.
2) Limiting the number of threads that are running at any given time.

线程池通过以下方式解决上述问题:1)在服务器启动时创建指定数量的线程,而不是在运行时创建它们。 2)限制在任何给定时间运行的线程数。

Note: The above is applicable for Thread Pools of Fixed Sizes.

注意:以上内容适用于固定大小的线程池。

#4


4  

You may assume Threads to be actual workers and Thread Pools to be group of workers. You may create multiple groups for various reasons like priority, purpose, etc. So, while one pool may be for general purpose tasks like background schedules, email broadcasting, etc. there might be a transaction processing pool to simultaneously process multiple transactions. In case of an Executor Service, I am sure you would not like to delay the transactional jobs to be completed after other non-critical activities like broadcasting confirmation emails or database maintenance activities are not completed. You may segregate them into pools and maintain them independently. That's a very simplistic answer without getting into technical jargons. Regards, KT

您可以将Threads视为实际工作者,将Thread Pools视为工作组。您可以出于各种原因创建多个组,例如优先级,目的等。因此,虽然一个池可能用于通用任务,例如后台计划,电子邮件广播等,但可能存在事务处理池以同时处理多个事务。对于Executor服务,我确信您不希望在其他非关键活动(如广播确认电子邮件或数据库维护活动)未完成之后延迟完成事务作业。您可以将它们分隔成池并独立维护它们。这是一个非常简单的答案,而不涉及技术术语。此致,KT

#5


4  

A simple Google search will result in a wealth of information regarding Java thread pools and thread pools in general.

简单的Google搜索通常会产生大量有关Java线程池和线程池的信息。

Here are some helpful links:

以下是一些有用的链接:

#6


1  

Thread pool is a pool of already created worker thread ready to do the job. It creates Thread and manage them. Instead of creating Thread and discarding them once task is done, thread-pool reuses threads in form of worker thread.

线程池是已经创建的工作线程池,可以完成工作。它创建线程并管理它们。完成任务后,线程池不再创建线程并丢弃它们,而是以工作线程的形式重用线程。

Why?

Because creation of Thread is time consuming process and it delays request processing. It also limits number of clients based upon how many thread per JVM is allowed, which is obviously a limited number.

因为创建Thread是一个耗时的过程并且它会延迟请求处理。它还根据每个JVM允许的线程数来限制客户端数量,这显然是有限的数量。


Create fixed size thread pool using Executor framework -

使用Executor框架创建固定大小的线程池 -

Java 5 introduced a full feature built-in Thread Pool framework commonly known as Executor framework.

Java 5引入了一个完整的内置线程池框架,通常称为Executor框架。

Creating fixed size thread pool using Java 5 Executor framework is pretty easy because of static factory methods provided by Executors class. All you need to do is define your task which you want to execute concurrently and than submit that task to ExecutorService.

使用Java 5 Executor框架创建固定大小的线程池非常简单,因为Executors类提供了静态工厂方法。您需要做的就是定义要同时执行的任务,而不是将该任务提交给ExecutorService。

From here, Thread pool will take care of how to execute that task; it can be executed by any free worker thread.

从这里开始,线程池将负责如何执行该任务;它可以由任何*工作线程执行。

public class ThreadPoolExample {
    public static void main(String args[]) {
       ExecutorService service = Executors.newFixedThreadPool(10); //create 10 worker threads in Thread Pool
       for (int i =0; i<100; i++){
           service.submit(new Task(i)); //submit that to be done 
       }
    }  
}

final class Task implements Runnable {
    private int taskId;  
    public Task(int id){
        this.taskId = id;
    }

    @Override
    public void run() {
        System.out.println("Task ID : " + this.taskId +" performed by " 
                           + Thread.currentThread().getName());
    }  
}

Output:
Task ID : 0 performed by pool-1-thread-1
Task ID : 3 performed by pool-1-thread-4
Task ID : 2 performed by pool-1-thread-3
Task ID : 1 performed by pool-1-thread-2
Task ID : 5 performed by pool-1-thread-6
Task ID : 4 performed by pool-1-thread-5

*Output may vary from system to system

#1


39  

A thread pool is a group of threads initially created that waits for jobs and executes them. The idea is to have the threads always existing, so that we won't have to pay overhead time for creating them every time. They are appropriate when we know there's a stream of jobs to process, even though there could be some time when there are no jobs.

线程池是最初创建的一组线程,它们等待作业并执行它们。我们的想法是让线程始终存在,这样我们就不必每次都花费很多时间来创建它们。当我们知道要处理的工作流时,它们是合适的,即使可能有一段时间没有工作。

Here's a nice diagram from Wikipedia: Java中的线程池有什么用?

这是*的一张很好的图表:

#2


6  

Thread Pools from the Java Tutorials has a good overview:

Java教程中的线程池有一个很好的概述:

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.

使用工作线程可以最大限度地减少线程创建带来的开销线程对象使用大量内存,在大型应用程序中,分配和释放许多线程对象会产生大量的内存管理开销。

#3


5  

Thread Pools are useful only in a Server-client kind of situation where the number/occurrence of client requests cannot be determined/predicted.

线程池仅在服务器 - 客户端类型的情况下有用,其中无法确定/预测客户端请求的数量/发生。

In this scenario, creating a new Thread each time a client request is made has two dis-advantages:

在这种情况下,每次发出客户端请求时创建一个新线程有两个不利之处:

1) Run time latency for thread creation: Creation of a thread requires some time, thus the actual job does not start as soon as the request comes in. The client may notice a slight delay.

1)线程创建的运行时延迟:创建线程需要一些时间,因此实际作业不会在请求进入后立即启动。客户端可能会注意到稍有延迟。

This criteria is crucial in interactive systems, where the client expects an immediate action.

此标准在交互式系统中至关重要,客户希望立即采取行动。

2) Uncontrolled use of System Resources: Threads consume system resources (memory etc.), thus the system may run out of resources in case there is an unprecedented flow of client requests.

2)系统资源的不受控制的使用:线程消耗系统资源(存储器等),因此在存在前所未有的客户端请求流的情况下,系统可能耗尽资源。

Thread pools address the above concerns by:
1) Creating specified number of threads on server start-up instead of creating them during the run-time.
2) Limiting the number of threads that are running at any given time.

线程池通过以下方式解决上述问题:1)在服务器启动时创建指定数量的线程,而不是在运行时创建它们。 2)限制在任何给定时间运行的线程数。

Note: The above is applicable for Thread Pools of Fixed Sizes.

注意:以上内容适用于固定大小的线程池。

#4


4  

You may assume Threads to be actual workers and Thread Pools to be group of workers. You may create multiple groups for various reasons like priority, purpose, etc. So, while one pool may be for general purpose tasks like background schedules, email broadcasting, etc. there might be a transaction processing pool to simultaneously process multiple transactions. In case of an Executor Service, I am sure you would not like to delay the transactional jobs to be completed after other non-critical activities like broadcasting confirmation emails or database maintenance activities are not completed. You may segregate them into pools and maintain them independently. That's a very simplistic answer without getting into technical jargons. Regards, KT

您可以将Threads视为实际工作者,将Thread Pools视为工作组。您可以出于各种原因创建多个组,例如优先级,目的等。因此,虽然一个池可能用于通用任务,例如后台计划,电子邮件广播等,但可能存在事务处理池以同时处理多个事务。对于Executor服务,我确信您不希望在其他非关键活动(如广播确认电子邮件或数据库维护活动)未完成之后延迟完成事务作业。您可以将它们分隔成池并独立维护它们。这是一个非常简单的答案,而不涉及技术术语。此致,KT

#5


4  

A simple Google search will result in a wealth of information regarding Java thread pools and thread pools in general.

简单的Google搜索通常会产生大量有关Java线程池和线程池的信息。

Here are some helpful links:

以下是一些有用的链接:

#6


1  

Thread pool is a pool of already created worker thread ready to do the job. It creates Thread and manage them. Instead of creating Thread and discarding them once task is done, thread-pool reuses threads in form of worker thread.

线程池是已经创建的工作线程池,可以完成工作。它创建线程并管理它们。完成任务后,线程池不再创建线程并丢弃它们,而是以工作线程的形式重用线程。

Why?

Because creation of Thread is time consuming process and it delays request processing. It also limits number of clients based upon how many thread per JVM is allowed, which is obviously a limited number.

因为创建Thread是一个耗时的过程并且它会延迟请求处理。它还根据每个JVM允许的线程数来限制客户端数量,这显然是有限的数量。


Create fixed size thread pool using Executor framework -

使用Executor框架创建固定大小的线程池 -

Java 5 introduced a full feature built-in Thread Pool framework commonly known as Executor framework.

Java 5引入了一个完整的内置线程池框架,通常称为Executor框架。

Creating fixed size thread pool using Java 5 Executor framework is pretty easy because of static factory methods provided by Executors class. All you need to do is define your task which you want to execute concurrently and than submit that task to ExecutorService.

使用Java 5 Executor框架创建固定大小的线程池非常简单,因为Executors类提供了静态工厂方法。您需要做的就是定义要同时执行的任务,而不是将该任务提交给ExecutorService。

From here, Thread pool will take care of how to execute that task; it can be executed by any free worker thread.

从这里开始,线程池将负责如何执行该任务;它可以由任何*工作线程执行。

public class ThreadPoolExample {
    public static void main(String args[]) {
       ExecutorService service = Executors.newFixedThreadPool(10); //create 10 worker threads in Thread Pool
       for (int i =0; i<100; i++){
           service.submit(new Task(i)); //submit that to be done 
       }
    }  
}

final class Task implements Runnable {
    private int taskId;  
    public Task(int id){
        this.taskId = id;
    }

    @Override
    public void run() {
        System.out.println("Task ID : " + this.taskId +" performed by " 
                           + Thread.currentThread().getName());
    }  
}

Output:
Task ID : 0 performed by pool-1-thread-1
Task ID : 3 performed by pool-1-thread-4
Task ID : 2 performed by pool-1-thread-3
Task ID : 1 performed by pool-1-thread-2
Task ID : 5 performed by pool-1-thread-6
Task ID : 4 performed by pool-1-thread-5

*Output may vary from system to system