Java中的线程池有什么用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3286626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the use of a Thread pool in Java?
提问by JavaUser
What is the use of a Thread pool? Is there a good real world example?
线程池有什么用?有一个很好的现实世界的例子吗?
采纳答案by Amir Rachum
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:
这是来自维基百科的一个很好的图表:
回答by Justin Ethier
Thread Poolsfrom 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.
使用工作线程可以最大限度地减少线程创建造成的开销。线程对象使用大量内存,在大型应用程序中,分配和取消分配许多线程对象会产生大量内存管理开销。
回答by S73417H
A simple Googlesearch will result in a wealth of information regarding Java thread pools and thread pools in general.
一个简单的谷歌搜索将得到大量关于 Java 线程池和一般线程池的信息。
Here are some helpful links:
以下是一些有用的链接:
回答by Kapil
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
你可以假设线程是实际的工作线程,线程池是一组工作线程。您可以出于各种原因(例如优先级、目的等)创建多个组。因此,虽然一个池可能用于后台计划、电子邮件广播等通用任务,但可能有一个事务处理池来同时处理多个事务。对于 Executor 服务,我相信您不希望在其他非关键活动(如广播确认电子邮件或数据库维护活动)未完成后延迟完成交易作业。您可以将它们隔离到池中并独立维护它们。这是一个非常简单的答案,没有涉及技术术语。问候, KT
回答by Avinash Ganta
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.
注意:以上适用于固定大小的线程池。
回答by roottraveller
Thread poolis 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.
线程池是一个已经创建的工作线程池,准备完成这项工作。它创建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
.
Executor
由于Executors
类提供了静态工厂方法,因此使用 Java 5框架创建固定大小的线程池非常容易。您需要做的就是定义要并发执行的任务,然后将该任务提交到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