MultiThreading与ThreadPoolExecutor

时间:2012-09-22 20:17:09

标签: java multithreading java.util.concurrent threadpoolexecutor

我在我编写的许多应用程序中使用过多线程。在阅读更多内容时,我遇到了ThreadPoolExecutors。我无法区分这两种情况。

我理解的是,当我有一项任务时,我应该使用多线程我想将任务分成多个小任务来利用CPU并更快地完成工作。当我设置任务时,使用ThreadPoolExecutor,每个任务可以彼此独立运行。

如果我错了,请纠正我。感谢

5 个答案:

答案 0 :(得分:18)

ThreadPoolExecutor只是一个高级API,使您可以在多个线程中运行任务,而无需处理低级Thread API。因此,区分多线程和ThreadPoolExecutor并没有多大意义。

ThreadPoolExecutor有很多种,但大多数都允许多个线程并行运行。通常,您可以使用Executor Service并使用Executors工厂。

例如,ExecutorService executor = Executors.newFixedThreadPool(10);将运行您在10个主题中提交的任务。

答案 1 :(得分:9)

ThreadPoolExecutor是进行多线程处理的一种方法。它通常在您

时使用
  1. 有独立的操作,不需要协调(虽然没有什么可以阻止你 从协调,但你必须小心)
  2. 希望限制一次执行的操作的容量,并且(可选)在执行时如果池正在所有线程中工作,则希望对操作进行排队。
  3. Java 7有另一个内置类,名为ForkJoinPool,通常用于Map-Reduce类型操作。例如,可以想象使用ForkJoinPool实现合并排序,方法是在每个叉点处将数组拆分为1/2,等待结果,并将结果合并在一起。

答案 2 :(得分:7)

线程池(执行器)是多线程的一种形式,特别是单个生产者的实现 - 多个消费者模式,其中线程重复将工作放入队列中以供工作线程团队执行。它使用常规线程实现,带来了一些好处:

  • 线程匿名 - 您没有明确控制哪个线程做什么;只需启动任务,它们将由游泳池处理。
  • 它封装了一个工作队列和线程团队 - 无需费心实现自己的线程安全队列和循环线程。
  • 负载平衡 - 由于工作人员在完成以前的任务时接受新任务,因此只要有足够多的任务可用,工作就会均匀分布。
  • 线程回收 - 只需在开始时创建一个单独的池,继续为其执行任务。每次工作都不需要继续启动和杀死线程。

鉴于上述情况,池确实适用于通常独立于彼此且通常短暂的任务(长I / O操作只会占用池中的线程,而无法使用做其他任务)。

答案 3 :(得分:1)

ThreadPoolExecutor是一种多线程形式,使用比直接使用线程更简单的API,您可以在其中提交任务。但是,任务可以提交其他任务,因此它们不需要是独立的。至于将任务划分为子任务,您可能会考虑在JDK7中使用新的fork / join API。

答案 4 :(得分:1)

来自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是实现并发的一种方法。实现并发有很多方法:

Executors框架提供了不同的API。下面列出了一些重要的API。

static ExecutorService  newFixedThreadPool(int nThreads)
  

创建一个线程池,该线程池重用在共享的无界队列中运行的固定数量的线程。

static ExecutorService  newCachedThreadPool()
  

创建一个根据需要创建新线程的线程池,但在它们可用时将重用以前构造的线程。

static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
  

创建一个线程池,可以安排命令在给定的延迟后运行,或者定期执行。

static ExecutorService  newWorkStealingPool()
  

使用所有可用处理器作为目标并行级别创建工作窃取线程池。

看看下面的SE问题:

java Fork/Join pool, ExecutorService and CountDownLatch

How to properly use Java Executor?