java 多线程与 ThreadPoolExecutor
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12547381/
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
MultiThreading Vs ThreadPoolExecutor
提问by Pit Digger
I have used multithreading in many of applications I wrote . While reading more I came across ThreadPoolExecutors
. I couldn't not differentiate between the two scenario wise .
我在我编写的许多应用程序中使用了多线程。在阅读更多时,我遇到了ThreadPoolExecutors
。我无法区分这两种情况。
Still what I understand is I should use multithreading when I have a task I want to divide a task in to multiple small tasks to utilize CPU and do the work faster . And use ThreadPoolExecutor
when I have a set to tasks and each task can be run independent of each other.
我仍然理解的是,当我有一个任务时我应该使用多线程,我想将一个任务分成多个小任务以利用 CPU 并更快地完成工作。而且使用ThreadPoolExecutor
的时候我有一组任务和每个任务可以运行相互独立的。
Please correct me if I am wrong . Thanks
如果我错了,请纠正我。谢谢
回答by assylias
A ThreadPoolExecutor
is just a high level API that enables you to run tasks in multiple threads while not having to deal with the low level Thread API. So it does not really make sense to differentiate between multithreading and ThreadPoolExecutor.
AThreadPoolExecutor
只是一个高级 API,它使您可以在多个线程中运行任务,而不必处理低级 Thread API。因此,区分多线程和 ThreadPoolExecutor 并没有什么意义。
There are many flavours of ThreadPoolExecutor
s, but most of them allow more than one thread to run in parallel. Typically, you would use an Executor Serviceand use the Executors
factory.
ThreadPoolExecutor
s有很多种,但大多数都允许多个线程并行运行。通常,您会使用Executor 服务并使用Executors
工厂。
For example, a ExecutorService executor = Executors.newFixedThreadPool(10);
will run the tasks you submit in 10 threads.
例如,aExecutorService executor = Executors.newFixedThreadPool(10);
将在 10 个线程中运行您提交的任务。
回答by Matt
ThreadPoolExecutor
is one way of doing multithreading. It's typically used when you
ThreadPoolExecutor
是进行多线程的一种方式。它通常用于当您
- have independent operations that don't require coordination (though nothing prevents you from coordinating, but you have to be careful)
- want to limit the capacity of how many operations you're executing at once, and (optionally) want to queue operations when for execution if the pool is currently working in all threads.
- 有不需要协调的独立操作(虽然没有什么可以阻止你协调,但你必须小心)
- 想要限制您一次执行的操作数量,并且(可选)想要在池当前在所有线程中工作时将操作排入队列以供执行。
Java 7 has another built in class called a ForkJoinPool
which is typically used for Map-Reduce type operations. For instance, one can imagine implementing a merge sort using a ForkJoinPool by splitting the array in 1/2 at each fork point, waiting for the results, and merging the results together.
Java 7 有另一个称为 a 的内置类ForkJoinPool
,它通常用于 Map-Reduce 类型的操作。例如,可以想象使用 ForkJoinPool 实现合并排序,方法是在每个分叉点将数组分成 1/2,等待结果,然后将结果合并在一起。
回答by Tudor
Thread pools (executors) are one form of multithreading, specifically an implementation of the single producer - multiple consumer pattern, in which a thread repeatedly puts work in a queue for a team of worker threads to execute. It is implemented using regular threads and brings several benefits:
线程池(执行器)是多线程的一种形式,特别是单生产者 - 多消费者模式的实现,其中一个线程重复地将工作放入队列中以供一组工作线程执行。它是使用常规线程实现的,并带来了几个好处:
- thread anonymity - you don't explicitly control which thread does what; just fire off tasks and they'll be handled by the pool.
- it encapsulates a work queue and thread team - no need to bother implementing you own thread-safe queue and looping threads.
- load-balancing - since workers take new tasks as they finish previous ones, work is uniformly distributed, provided there is a sufficiently large number of tasks available.
- thread recycling - just create a single pool at the beginning an keep feeding it tasks. No need to keep starting and killing threads every time work needs to be done.
- 线程匿名——你没有明确控制哪个线程做什么;只需触发任务,它们就会由池处理。
- 它封装了一个工作队列和线程组——无需费心实现你自己的线程安全队列和循环线程。
- 负载平衡 - 由于工作人员在完成以前的任务时接受新任务,因此只要有足够多的可用任务,工作就会均匀分布。
- 线程回收 - 只需在开始时创建一个池并继续为其提供任务。无需在每次需要完成工作时不断启动和终止线程。
Given the above, it is true that pools are suited for tasks that are usually independent of each-other and usually short-lived (long I/O operations will just tie up threads from the pool that won't be able to do other tasks).
综上所述,池确实适用于通常相互独立且通常生命周期较短的任务(长时间的 I/O 操作只会占用池中无法执行其他任务的线程) )。
回答by Frank Pavageau
ThreadPoolExecutor is a form of multithreading, with a simpler API to use than directly using Threads, where you submit tasks indeed. However, tasks can submit other tasks, so they need not be independent. As for the division of tasks into sub-tasks, you may be thinking of the new fork/join API in JDK7.
ThreadPoolExecutor 是一种多线程形式,与直接使用 Threads 相比,它具有更简单的 API 使用,您确实可以在其中提交任务。但是,任务可以提交其他任务,因此它们不必是独立的。至于将任务划分为子任务,你可能会想到JDK7中新的fork/join API。
回答by Ravindra babu
From source code documentation of ThreadPoolExecutor
来自ThreadPoolExecutor 的源代码文档
/*
* <p>Thread pools address two different problems: they usually
* provide improved performance when executing large numbers of
* asynchronous tasks, due to reduced per-task invocation overhead,
* and they provide a means of bounding and managing the resources,
* including threads, consumed when executing a collection of tasks.
* Each {@code ThreadPoolExecutor} also maintains some basic
* statistics, such as the number of completed tasks.
*
* <p>To be useful across a wide range of contexts, this class
* provides many adjustable parameters and extensibility
* hooks. However, programmers are urged to use the more convenient
* {@link Executors} factory methods {@link
* Executors#newCachedThreadPool} (unbounded thread pool, with
* automatic thread reclamation), {@link Executors#newFixedThreadPool}
* (fixed size thread pool) and {@link
* Executors#newSingleThreadExecutor} (single background thread), that
* preconfigure settings for the most common usage
* scenarios.
*/
ThreadPoolExecutor
is one way of achieving concurrency. There are many ways in achieving concurrency :
ThreadPoolExecutor
是实现并发的一种方式。实现并发的方法有很多:
Executorsframework provides different APIs. Some of important APIs are listed below.
Executors框架提供了不同的 API。下面列出了一些重要的 API。
static ExecutorService newFixedThreadPool(int nThreads)
Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue.
创建一个线程池,该线程池重用固定数量的线程在共享的无界队列中运行。
static ExecutorService newCachedThreadPool()
Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.
创建一个线程池,根据需要创建新线程,但在可用时将重用先前构造的线程。
static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.
创建一个线程池,可以安排命令在给定延迟后运行,或定期执行。
static ExecutorService newWorkStealingPool()
Creates a work-stealing thread pool using all available processors as its target parallelism level.
使用所有可用处理器作为其目标并行度级别来创建窃取工作的线程池。
Have a look at below SE questions:
看看下面的 SE 问题:
java Fork/Join pool, ExecutorService and CountDownLatch
java Fork/Join 池、ExecutorService 和 CountDownLatch