MultiThreading与ThreadPoolExecutor

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

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

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

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

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

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

ThreadPoolExecutor是进行multithreading处理的一种方式。 它通常在您使用时使用

  1. 有独立的操作,不需要协调(虽然没有什么阻止你协调,但你必须小心)
  2. 想要限制一次执行多少操作的容量,并且(可选)如果池当前在所有线程中工作,则希望在执行时排队操作。

Java 7有另一个内置类,叫做ForkJoinPool ,它通常用于Map-Reduce类型的操作。 例如,可以想象使用ForkJoinPool实现合并排序,方法是在每个叉点处将数组拆分为1/2,等待结果,并将结果合并在一起。

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

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

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

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

从ThreadPoolExecutor的源代码文档

 /* * 

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. * *

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. */