JAVA 线程池 ExecutorService Callable Future

2024-03-18 04:18

本文主要是介绍JAVA 线程池 ExecutorService Callable Future,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

接口 Java.util.concurrent.ExecutorService 表述了异步执行的机制,并且可以让任务在后台执行。壹個 ExecutorService 实例因此特别像壹個线程池。事实上,在 java.util.concurrent 包中的 ExecutorService 的实现就是壹個线程池的实现。

ExecutorService 样例

这里有壹個简单的使用Java 实现的 ExectorService 样例:
[java]  view plain copy
在CODE上查看代码片 派生到我的代码片
  1. ExecutorService executorService = Executors.newFixedThreadPool(10);  
  2.   
  3. executorService.execute(new Runnable() {  
  4.     public void run() {  
  5.         System.out.println("Asynchronous task");  
  6.     }  
  7. });  
  8.   
  9. executorService.shutdown();  
首先使用 newFixedThreadPool() 工厂方法创建壹個 ExecutorService ,上述代码创建了壹個可以容纳10個线程任务的线程池。其次,向 execute() 方法中传递壹個异步的 Runnable 接口的实现,这样做会让 ExecutorService 中的某個线程执行这個 Runnable 线程。

任务的委托(Task Delegation)

下方展示了一个线程的把任务委托异步执行的ExecutorService的示意图。

壹旦线程把任务委托给 ExecutorService,该线程就会继续执行与运行任务无关的其它任务。

ExecutorService 的实现

由于 ExecutorService 只是壹個接口,你壹量需要使用它,那麽就需要提供壹個该接口的实现。ExecutorService 接口在 java.util.concurrent 包中有如下实现类:
  • ThreadPoolExecutor
  • ScheduledThreadPoolExecutor

创建壹個 ExecutorService

你可以根据自己的需要来创建壹個 ExecutorService ,也可以使用 Executors 工厂方法来创建壹個 ExecutorService 实例。这里有几個创建 ExecutorService 的例子:

[java]  view plain copy
在CODE上查看代码片 派生到我的代码片
  1. ExecutorService executorService1 = Executors.newSingleThreadExecutor();  
  2. ExecutorService executorService2 = Executors.newFixedThreadPool(10);  
  3. ExecutorService executorService3 = Executors.newScheduledThreadPool(10);  

ExecutorService 使用方法

这里有几种不同的方式让你将任务委托给壹個 ExecutorService:

[java]  view plain copy
在CODE上查看代码片 派生到我的代码片
  1. execute(Runnable)  
  2. submit(Runnable)  
  3. submit(Callable)  
  4. invokeAny(...)  
  5. invokeAll(...)  
我会在接下来的内容里把每個方法都看壹遍。

execute(Runnable)

方法 execute(Runnable) 接收壹個 java.lang.Runnable 对象作为参数,并且以异步的方式执行它。如下是壹個使用 ExecutorService 执行 Runnable 的例子:

[java]  view plain copy
在CODE上查看代码片 派生到我的代码片
  1. ExecutorService executorService = Executors.newSingleThreadExecutor();  
  2.   
  3. executorService.execute(new Runnable() {  
  4.     public void run() {  
  5.         System.out.println("Asynchronous task");  
  6.     }  
  7. });  
  8.       
  9. executorService.shutdown();  
使用这种方式没有办法获取执行 Runnable 之后的结果,如果你希望获取运行之后的返回值,就必须使用 接收 Callable 参数的 execute() 方法,后者将会在下文中提到。

submit(Runnable)

方法 submit(Runnable) 同样接收壹個 Runnable 的实现作为参数,但是会返回壹個 Future 对象。这個 Future 对象可以用于判断 Runnable 是否结束执行。如下是壹個 ExecutorService 的 submit() 方法的例子:

[java]  view plain copy
在CODE上查看代码片 派生到我的代码片
  1. Future future = executorService.submit(new Runnable() {  
  2.     public void run() {  
  3.         System.out.println("Asynchronous task");  
  4.     }  
  5. });  
  6. //如果任务结束执行则返回 null  
  7. System.out.println("future.get()=" + future.get());  

submit(Callable)

方法 submit(Callable) 和方法 submit(Runnable) 比较类似,但是区别则在于它们接收不同的参数类型。Callable 的实例与 Runnable 的实例很类似,但是 Callable 的 call() 方法可以返回壹個结果。方法 Runnable.run() 则不能返回结果。

Callable 的返回值可以从方法 submit(Callable) 返回的 Future 对象中获取。如下是壹個 ExecutorService Callable 的样例:

[java]  view plain copy
在CODE上查看代码片 派生到我的代码片
  1. Future future = executorService.submit(new Callable(){  
  2.     public Object call() throws Exception {  
  3.         System.out.println("Asynchronous Callable");  
  4.         return "Callable Result";  
  5.     }  
  6. });  
  7.   
  8. System.out.println("future.get() = " + future.get());  

上述样例代码会输出如下结果:
[java]  view plain copy
在CODE上查看代码片 派生到我的代码片
  1. ExecutorService executorService = Executors.newSingleThreadExecutor();  
  2.   
  3. Set<Callable<String>> callables = new HashSet<Callable<String>>();  
  4.   
  5. callables.add(new Callable<String>() {  
  6.     public String call() throws Exception {  
  7.         return "Task 1";  
  8.     }  
  9. });  
  10. callables.add(new Callable<String>() {  
  11.     public String call() throws Exception {  
  12.         return "Task 2";  
  13.     }  
  14. });  
  15. callables.add(new Callable<String>() {  
  16.     public String call() throws Exception {  
  17.         return "Task 3";  
  18.     }  
  19. });  
  20.   
  21. String result = executorService.invokeAny(callables);  
  22.   
  23. System.out.println("result = " + result);  
  24.   
  25. executorService.shutdown();  

inVokeAny()

方法 invokeAny() 接收壹個包含 Callable 对象的集合作为参数。调用该方法不会返回 Future 对象,而是返回集合中某壹個 Callable 对象的结果,而且无法保证调用之后返回的结果是哪壹個 Callable,只知道它是这些 Callable 中壹個执行结束的 Callable 对象。
如果壹個任务运行完毕或者抛出异常,方法会取消其它的 Callable 的执行。
以下是壹個样例:

[java]  view plain copy
在CODE上查看代码片 派生到我的代码片
  1. ExecutorService executorService = Executors.newSingleThreadExecutor();  
  2.   
  3. Set<Callable<String>> callables = new HashSet<Callable<String>>();  
  4.   
  5. callables.add(new Callable<String>() {  
  6.     public String call() throws Exception {  
  7.         return "Task 1";  
  8.     }  
  9. });  
  10. callables.add(new Callable<String>() {  
  11.     public String call() throws Exception {  
  12.         return "Task 2";  
  13.     }  
  14. });  
  15. callables.add(new Callable<String>() {  
  16.     public String call() throws Exception {  
  17.         return "Task 3";  
  18.     }  
  19. });  
  20.   
  21. String result = executorService.invokeAny(callables);  
  22.   
  23. System.out.println("result = " + result);  
  24.   
  25. executorService.shutdown();  
以上样例代码会打印出在给定的集合中的某壹個 Callable 的返回结果。我尝试运行了几次,结果都在改变。有时候返回结果是"Task 1",有时候是"Task 2",等等。

invokeAll()

方法 invokeAll() 会调用存在于参数集合中的所有 Callable 对象,并且返回壹個包含 Future 对象的集合,你可以通过这個返回的集合来管理每個 Callable 的执行结果。
需要注意的是,任务有可能因为异常而导致运行结束,所以它可能并不是真的成功运行了。但是我们没有办法通过 Future 对象来了解到这個差异。
以下是壹個代码样例:

[java]  view plain copy
在CODE上查看代码片 派生到我的代码片
  1. ExecutorService executorService = Executors.newSingleThreadExecutor();  
  2.   
  3. Set<Callable<String>> callables = new HashSet<Callable<String>>();  
  4.   
  5. callables.add(new Callable<String>() {  
  6.     public String call() throws Exception {  
  7.         return "Task 1";  
  8.     }  
  9. });  
  10. callables.add(new Callable<String>() {  
  11.     public String call() throws Exception {  
  12.         return "Task 2";  
  13.     }  
  14. });  
  15. callables.add(new Callable<String>() {  
  16.     public String call() throws Exception {  
  17.         return "Task 3";  
  18.     }  
  19. });  
  20.   
  21. String result = executorService.invokeAny(callables);  
  22.   
  23. System.out.println("result = " + result);  
  24.   
  25. executorService.shutdown();  

ExecuteService 服务的关闭

当使用 ExecutorService 完毕之后,我们应该关闭它,这样才能保证线程不会继续保持运行状态。 
举例来说,如果你的程序通过 main() 方法启动,并且主线程退出了你的程序,如果你还有壹個活动的 ExecutorService 存在于你的程序中,那么程序将会继续保持运行状态。存在于 ExecutorService 中的活动线程会阻止Java虚拟机关闭。
为了关闭在 ExecutorService 中的线程,你需要调用 shutdown() 方法。ExecutorService 并不会马上关闭,而是不再接收新的任务,壹但所有的线程结束执行当前任务,ExecutorServie 才会真的关闭。所有在调用 shutdown() 方法之前提交到 ExecutorService 的任务都会执行。
如果你希望立即关闭 ExecutorService,你可以调用 shutdownNow() 方法。这個方法会尝试马上关闭所有正在执行的任务,并且跳过所有已经提交但是还没有运行的任务。但是对于正在执行的任务,是否能够成功关闭它是无法保证的,有可能他们真的被关闭掉了,也有可能它会壹直执行到任务结束。这是壹個最好的尝试。

本文英文原文链接:http://tutorials.jenkov.com/java-util-concurrent/executorservice.html#executorservice-example ,中文译文首发开源中国社区 http://my.oschina.net/bairrfhoinn/blog/177639,转载请注明原始出处。

这篇关于JAVA 线程池 ExecutorService Callable Future的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/821143

相关文章

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd