本文介绍了使用 ExecutorService 有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 ExecutorService 与将 Runnable 传递给 Thread 构造函数的运行线程相比有什么优势?

解决方案

ExecutorService 抽象了许多与原始 Thread 等低级抽象相关的复杂性.它提供了在任务成功或突然终止时安全启动、关闭、提交、执行和阻塞的机制(表示为 RunnableCallable).

来自 JCiP,第 6.2 节,直接来自马口:

Executor 可能是一个简单的接口,但它构成了一个灵活而强大的异步任务执行框架的基础,该框架支持多种任务执行策略.它提供了一种将任务提交任务执行解耦的标准方法,将任务描述为Runnable.Executor 实现还提供生命周期支持和挂钩,用于添加统计信息收集、应用程序管理和监控....使用 Executor 通常是在应用程序中实现生产者-消费者设计的最简单途径.

与其花费时间(通常是错误的,并且需要付出很大的努力)实现并行的底层基础架构,j.u.concurrent 框架让您可以专注于构建任务、依赖项和潜在的并行性.对于大量并发应用程序,识别和利用任务边界并利用 juc 很简单,让您可以专注于真正并发挑战的小得多的子集,这可能需要更专业的解决方案.

此外,尽管样板外观和感觉,总结并发实用程序的 Oracle API 页面包括一些使用它们的非常可靠的论据,尤其是:

开发人员很可能已经了解标准库类,所以没有必要学习ad-hoc 的 API 和行为并发组件.此外,并发应用相距甚远构建时更易于调试可靠且经过良好测试的组件.

这个关于SO的问题询问一本好书,立即回答是 JCiP.如果您还没有,请给自己一份副本.那里介绍的综合性并发方法远远超出了这个问题,从长远来看,它将为您省去很多心痛.

What is the advantage of using ExecutorService over running threads passing a Runnable into the Thread constructor?

解决方案

ExecutorService abstracts away many of the complexities associated with the lower-level abstractions like raw Thread. It provides mechanisms for safely starting, closing down, submitting, executing, and blocking on the successful or abrupt termination of tasks (expressed as Runnable or Callable).

From JCiP, Section 6.2, straight from the horse's mouth:

Rather than spending your time implementing (often incorrectly, and with great effort) the underlying infrastructure for parallelism, the j.u.concurrent framework allows you to instead focus on structuring tasks, dependencies, potential parallelism. For a large swath of concurrent applications, it is straightforward to identify and exploit task boundaries and make use of j.u.c, allowing you to focus on the much smaller subset of true concurrency challenges which may require more specialized solutions.

Also, despite the boilerplate look and feel, the Oracle API page summarizing the concurrency utilities includes some really solid arguments for using them, not least:

This question on SO asks about a good book, to which the immediate answer is JCiP. If you haven't already, get yourself a copy. The comprehensive approach to concurrency presented there goes well beyond this question, and will save you a lot of heartache in the long run.

这篇关于使用 ExecutorService 有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:01
查看更多