当前位置: 首页 > 编程日记 > 正文

ExecutorService 的理解与使用

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

ExecutorService 样例

这里有壹個简单的使用Java 实现的 ExectorService 样例:

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 接口在 java.util.concurrent 包中有如下实现类:

  • ThreadPoolExecutor
  • ScheduledThreadPoolExecutor

创建壹個 ExecutorService

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

ExecutorService executorService1 = Executors.newSingleThreadExecutor();  
ExecutorService executorService2 = Executors.newFixedThreadPool(10);  
ExecutorService executorService3 = Executors.newScheduledThreadPool(10);

ExecutorService 使用方法

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

    execute(Runnable)  submit(Runnable)  submit(Callable)  invokeAny(...)  invokeAll(...)  

ExecutorService 使用方法我会在接下来的内容里把每個方法都看壹遍。

execute(Runnable)

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

    ExecutorService executorService = Executors.newSingleThreadExecutor();  executorService.execute(new Runnable() {  public void run() {  System.out.println("Asynchronous task");  }  });  executorService.shutdown();  

使用这种方式没有办法获取执行 Runnable 之后的结果,如果你希望获取运行之后的返回值,就必须使用 接收 Callable 参数的 execute() 方法,后者将会在下文中提到。

submit(Runnable)

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

    Future future = executorService.submit(new Runnable() {  public void run() {  System.out.println("Asynchronous task");  }  });  //如果任务结束执行则返回 null  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 的样例:

    Future future = executorService.submit(new Callable(){  public Object call() throws Exception {  System.out.println("Asynchronous Callable");  return "Callable Result";  }  });  System.out.println("future.get() = " + future.get());  

上述样例代码会输出如下结果:

    ExecutorService executorService = Executors.newSingleThreadExecutor();  Set<Callable<String>> callables = new HashSet<Callable<String>>();  callables.add(new Callable<String>() {  public String call() throws Exception {  return "Task 1";  }  });  callables.add(new Callable<String>() {  public String call() throws Exception {  return "Task 2";  }  });  callables.add(new Callable<String>() {  public String call() throws Exception {  return "Task 3";  }  });  String result = executorService.invokeAny(callables);  System.out.println("result = " + result);  executorService.shutdown();  

inVokeAny()

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

    ExecutorService executorService = Executors.newSingleThreadExecutor();  Set<Callable<String>> callables = new HashSet<Callable<String>>();  callables.add(new Callable<String>() {  public String call() throws Exception {  return "Task 1";  }  });  callables.add(new Callable<String>() {  public String call() throws Exception {  return "Task 2";  }  });  callables.add(new Callable<String>() {  public String call() throws Exception {  return "Task 3";  }  });  String result = executorService.invokeAny(callables);  System.out.println("result = " + result);  executorService.shutdown();  

以上样例代码会打印出在给定的集合中的某壹個 Callable 的返回结果。我尝试运行了几次,结果都在改变。有时候返回结果是"Task 1",有时候是"Task 2",等等。

invokeAll()

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

    ExecutorService executorService = Executors.newSingleThreadExecutor();  Set<Callable<String>> callables = new HashSet<Callable<String>>();  callables.add(new Callable<String>() {  public String call() throws Exception {  return "Task 1";  }  });  callables.add(new Callable<String>() {  public String call() throws Exception {  return "Task 2";  }  });  callables.add(new Callable<String>() {  public String call() throws Exception {  return "Task 3";  }  });  String result = executorService.invokeAny(callables);  System.out.println("result = " + result);  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,转载请注明原始出处。

转载于:https://www.cnblogs.com/zy-jiayou/p/7250229.html

相关文章:

前后端交互,网络请求

这边文章主要根据我自己的前端开发工作经验&#xff0c;东拼西凑出来的一点理解&#xff0c;希望能够对大家有点帮助&#xff0c;如果有误导或者错误的地方还请帮助指正&#xff0c;感谢&#xff01;&#xff01;&#xff01; 前后端交互我理解主要分为三个主要的部分&#xf…

HDU 1877 另一个版本 A+B

另一个版本 AB Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 12894 Accepted Submission(s): 4901Problem Description输入两个不超过整型定义的非负10进制整数A和B(<231-1)。输出AB的m (1 < m <10…

gatsby_如何使用Gatsby.js来获取内容

gatsbyby Dimitri Ivashchuk由Dimitri Ivashchuk 如何使用Gatsby.js来获取内容 (How to source content with Gatsby.js) Gatsby.js is a powerful static site generator (with dynamic capabilities) which can be used to build super performant web-sites. It has a very…

使用 AFNetworking 进行 XML 和 JSON 数据请求

&#xff08;1&#xff09;XML 数据请求 使用 AFNetworking 中的 AFHTTPRequestOperation 和 AFXMLParserResponseSerializer&#xff0c;另外结合第三方框架 XMLDictionary 进行数据转换 使用 XMLDictionary 的好处&#xff1a;有效避免自行实现 NSXMLParserDelegate 委托代理…

批处理+定时任务实现定时休息提醒

前言&#xff1a;俗话说的好&#xff0c;懒是第一生产力&#xff0c;懒是提高生产效率的必要条件。而现今windows是大部分人的第一生产工具&#xff0c;批处理定时任务这对黄金搭档就是提升生产效率的第一工具。大家在生产过程中经常会遇到各种周期性的重复的工作&#xff0c;比…

后端返回的数据中换行符 html换行

标签代码 <span v-html"model3_txt"></span> vue js代码 var txt "恭喜你\n获得某某某奖品"; if(txt.indexOf(\n)!-1){var reg new RegExp("/r/n", "g");txttxt.replace(reg, "<br/>");console.log(t…

vim block vim_如何不再害怕Vim

vim block vim精选最流行的命令以及如何使用它们 (A curation of the most popular commands and how to use them) If you’ve ever used Vim, you know how difficult it can get to reach the same speed as in a “normal” GUI editor. But once you do, the payoff is ex…

android EditText 限定中文个数与英文个数的解决方式

EditText 限定中文8个英文16个的解决方法。 在EditText上控件提供的属性中有限定最大最小长度的方法。可是&#xff0c;对于输入时&#xff0c;限定中文8个英文16个时&#xff0c;怎么办&#xff1f;相当于一个中文的长度是两个英文的长度。原理就不说了。自己看一下android的源…

根据二叉树的前序遍历和中序遍历重建二叉树

题目描述 输入某二叉树的前序遍历和中序遍历的结果&#xff0c;请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}&#xff0c;则重建二叉树并返回。1 /**2 * Definition for …

VUE 监听当前路由 侦听器 watch

侦听器&#xff1a; 你可以利用侦听器&#xff0c;响应数据的变化&#xff0c;例如路由&#xff0c;和页面中data的值&#xff0c;可以在他们变化的时候写相应的处理逻辑在侦听器中。 侦听器的使用很简单&#xff1a; watch 对象就是侦听器&#xff0c;只有当侦听的值改变了它…

如何使用Bootstrap4和ES6创建自定义确认框

by Prashant Yadav通过Prashant Yadav 如何使用Bootstrap4和ES6创建自定义确认框 (How to create a custom confirm box with Bootstrap4 and ES6) We put lots of sweat into achieving a good design, but imagine a scenario where we have to use something which is styl…

RequireJS学习笔记(转)

前言进入移动前端是很不错的选择&#xff0c;这块也是我希望的道路&#xff0c;但是不熟悉啊。。。现在项目用的是requirebackbone&#xff0c;整个框架被封装了一次&#xff0c;今天看了代码搞不清楚&#xff0c;觉得应该先从源头抓起&#xff0c;所以再看看require了。上午是…

火狐中的table

在火狐浏览器中&#xff0c;table的th、td会存在小数转载于:https://www.cnblogs.com/likwin/p/7270817.html

React路由 react-router-dom

React的路由&#xff1a; 首先我们创建一个React应用 npm install -g create-react-app create-react-app demo-app cd demo-app安装路由 npm install react-router-dom npm add babel/runtime 接下来&#xff0c;将以下任一示例复制/粘贴到中src/App.js。 第一个示例&…

编程基础 垃圾回收_为什么我回收编程问题

编程基础 垃圾回收by Amy M Haddad通过艾米M哈达德(Amy M Haddad) 为什么我回收编程问题 (Why I Recycle Programming Problems) Many programmers are given the same advice: solve as many problems as possible. It’s true that solving new problems can help you gain …

SQL Server孤立账户解决办法

选择你想要的数据库。 执行 exec sp_change_users_login UPDATE_ONE,用户名,登录名 假如你的登录名是&#xff1a;sd exec sp_change_users_login UPDATE_ONE,sd,sd 转载于:https://www.cnblogs.com/runliuv/p/7273675.html

vue更新data无效,页面data没刷新 vue.set

Vue中组件的data是有很多坑的&#xff0c;先普及一下常识&#xff1a; 1.想使用data&#xff0c;必须先在data中创建。&#xff08;如果不创建就会报错&#xff09;示例&#xff1a; <div class"">{{user.Age}}</div>new Vue({el: #app,data: {user:{A…

重温Thinking in java

1、高精度 BigInteger、BigDecimal 支持任意大小的数字 不能使用运算符 运算速度相对于int、float稍慢 2、对象作用域 {String s new String("aaa"); } 在}外 此时栈中的引用s已经超出了自己的作用域 便不存在了 但是new String("aaa")这个堆中的对象仍然…

2018 react 大会_React Conf 2018的经验教训

2018 react 大会by Yangshun Tay阳顺泰 React Conf 2018的经验教训 (Lessons Learned at React Conf 2018) I was fortunate to have attended React Conf 2018 thanks to my managers — it was an awesome event. I have been watching past React Conf videos online and i…

删除url中某个参数

这里的url 是指一个网站链接 例如&#xff1a; https://baidu.com?a1&b2 下面看一下封装的代码 <!DOCTYPE html> <html><head><meta charset"utf-8"><script src"https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js&q…

【转载】MSXML应用总结 开发篇(下)

原文&#xff1a;http://blog.sina.com.cn/s/blog_48f93b530100eq4b.html 三、查询XML文档节点 这部分属于“读”XML文档并做节点遍历&#xff0c;由于担心加上实例会占用过多的篇幅影响阅读&#xff0c;先在这篇做方法总结&#xff0c;以后有时间再写一篇“实战篇”专门写个实…

d010:盈数、亏数和完全数

题目: 对一个正整数N而言&#xff0c;将它除了本身以外所有的因子加起来的总和为S&#xff0c;如果S>N&#xff0c;则N为盈数&#xff0c;如果S<N&#xff0c;则N为亏数&#xff0c;而如果SN&#xff0c;则N为完全数&#xff08;Perfect Number&#xff09;。例如10的因子…

软件开发 理想_我如何在12个月内找到理想的软件工作

软件开发 理想In this talk, Matt Woods shares the 3 cornerstone habits that helped him land his dream software job in just 12 months. These habits paved the way for him to consistently grow as a software developer, balloon his professional network, and easi…

Angular4.0从入门到实战打造在线竞拍网站学习笔记之四--数据绑定管道

Angular4.0基础知识之组件Angular4.0基础知识之路由Angular4.0依赖注入Angular4.0数据绑定&管道 数据绑定 数据绑定允许你将组件控制器的属性和方法与组件的模板连接起来&#xff0c;大大降低了开发时的编码量。 常见的表现形式有&#xff1a; 插值表达式&#xff1a;<h…

给GridView增加求和行

1、在WebForm窗体中&#xff0c;设置GridView的ShowFooter"True" 2、在后台代码中 private int jhrs0,ybrs0;//定义变量 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowIndex > 0) { jhrs Convert.ToInt16(e.Ro…

phpMyAdmin 数据库添加int类型的值时默认设为唯一主键的问题解决

数据库的表中插入了一条数据&#xff0c;再插入数据就插入不进去。 这是我今天在开发数据库的时候&#xff0c;遇到一个问题&#xff0c;经过排查&#xff0c;是数据库的结构有问题&#xff0c;有字段是唯一数据&#xff0c;但是目前还不想设置它的值。 场景环境描述&#xff…

python 类中定义类_Python中的动态类定义

python 类中定义类Here’s a neat Python trick you might just find useful one day. Let’s look at how you can dynamically define classes, and create instances of them as required.这是一个整洁的Python技巧&#xff0c;有一天可能会有用。 让我们看一下如何动态定义…

用自定义方法,传入成绩数组,实现输出考试成绩的成三名

package com.imooc; import java.util.Arrays; //导入Array类包 import java.util.Scanner; //导入Scanner类包 public class Final2 { public static void main(String args[]){Scanner…

EJS 什么是EJS后缀文件 EJS怎么用

一、什么是EJS EJS是一个JavaScript模板库&#xff0c;用来从JSON数据中生成HTML字符串。 二、为什么要使用EJS 与最初的JavaScript相比较&#xff0c;一些不太了解你的代码的人可以更容易地通过EJS模板代码看得懂你的代码。 让我们放松一下&#xff0c;一起来享受下令人激动的…

一个推荐系统,实现完整的设计-在百度搜索关键词推荐案例

在之前一篇博文中&#xff0c; 有同学在评论中问了个问题&#xff1a; 怎样解决因式分解带来的推荐冷门。热门关键词的问题。 在回答这个问题的时候&#xff0c; 想到了近几年在做搜索推荐系统的过程中&#xff0c; 学术界和工业界的一些差别。 正好近期正在做技术规划&#xf…