ExecutorService的submit方法使用
五、ExecutorService的execute和submit方法区别,以及submit使用的具体Demo
1、接收的参数不一样
2、submit有返回值,而execute没有
Method submit extends base method Executor.execute by creating and returning a Future that can be used to cancel execution and/or wait for completion.
用到返回值的例子,比如说我有很多个做validation的task,我希望所有的task执行完,然后每个task告诉我它的执行结果,是成功还是失败,如果是失败,原因是什么。然后我就可以把所有失败的原因综合起来发给调用者。
个人觉得cancel execution这个用处不大,很少有需要去取消执行的。
而最大的用处应该是第二点。
3、submit方便Exception处理
There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute
this exception will Go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err
). If you submitted the task with submit
any thrown exception, checked or not, is then part of the task's return status. For a task that was submitted with submit
and that terminates with an exception, the Future.get
will rethrow this exception, wrapped in an ExecutionException
.
意思就是如果你在你的task里会抛出checked或者unchecked exception,而你又希望外面的调用者能够感知这些exception并做出及时的处理,那么就需要用到submit,通过捕获Future.get抛出的异常。
比如说,我有很多更新各种数据的task,我希望如果其中一个task失败,其它的task就不需要执行了。那我就需要catch Future.get抛出的异常,然后终止其它task的执行,代码如下:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*; /**
* Created by caoliu on 2017/8/18.
*/
public class ExecutorServiceTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
List<Future<String>> resultList = new ArrayList<>(); // 创建10个任务并执行
for (int i = 0; i < 10; i++) {
// 使用ExecutorService执行Callable类型的任务,并将结果保存在future变量中
Future<String> future = executorService.submit(new TaskWithResult(i));
// 将任务执行结果存储到List中
resultList.add(future);
}
executorService.shutdown(); // 遍历任务的结果
for (Future<String> fs : resultList) {
try {
System.out.println(fs.get()); // 打印各个线程(任务)执行的结果
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
executorService.shutdownNow();
e.printStackTrace();
return;
}
}
}
}
class TaskWithResult implements Callable<String> {
private int id; public TaskWithResult(int id) {
this.id = id;
} /**
* 任务的具体过程,一旦任务传给ExecutorService的submit方法,则该方法自动在一个线程上执行。
*
* @return
* @throws Exception
*/
public String call() throws Exception {
System.out.println("call()方法被自动调用,干活!!! " + Thread.currentThread().getName());
//下面的判读是模拟一个抛出异常的操作
if (new Random().nextBoolean())
throw new TaskException("Meet error in task." + Thread.currentThread().getName());
// 一个模拟耗时的操作
for (int i = 999999999; i > 0; i--)
;
return "call()方法被自动调用,任务的结果是:" + id + " " + Thread.currentThread().getName();
}
}
class TaskException extends Exception {
public TaskException(String message) {
super(message);
}
}
下面是控制台输出的结果:
call()方法被自动调用,干活!!! pool-1-thread-1
call()方法被自动调用,干活!!! pool-1-thread-4
call()方法被自动调用,干活!!! pool-1-thread-3
call()方法被自动调用,干活!!! pool-1-thread-2
call()方法被自动调用,干活!!! pool-1-thread-5
call()方法被自动调用,干活!!! pool-1-thread-6
call()方法被自动调用,干活!!! pool-1-thread-7
call()方法被自动调用,干活!!! pool-1-thread-4
call()方法被自动调用,干活!!! pool-1-thread-8
call()方法被自动调用,干活!!! pool-1-thread-9
java.util.concurrent.ExecutionException: TaskException: Meet error in task.pool-1-thread-1
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:188)
at ExecutorServiceTest.main(ExecutorServiceTest.java:26)
Caused by: TaskException: Meet error in task.pool-1-thread-1
at TaskWithResult.call(ExecutorServiceTest.java:54)
at TaskWithResult.call(ExecutorServiceTest.java:37)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745) Process finished with exit code 0
ExecutorService的submit方法使用的更多相关文章
- ExecutorService的submit方法的坑
先看一段代码: public Future<?> submit(Runnable task) { if (task == null) throw new NullPointerExcept ...
- ExecutorService的execute和submit方法
三个区别: 1.接收的参数不一样 2.submit有返回值,而execute没有 Method submit extends base method Executor.execute by creat ...
- ExecutorService中submit和execute的区别(转)
在Java5之后,并发线程这块发生了根本的变化,最重要的莫过于新的启动.调度.管理线程的一大堆API了.在Java5以后,通过Executor来启动线程比用Thread的start()更好.在新特征中 ...
- ExecutorService中submit和execute的区别
在Java5之后,并发线程这块发生了根本的变化,最重要的莫过于新的启动.调度.管理线程的一大堆API了.在Java5以后,通过Executor来启动线程比用Thread的start()更好.在新特征中 ...
- ExecutorService中submit和execute的区别<转>
在Java5之后,并发线程这块发生了根本的变化,最重要的莫过于新的启动.调度.管理线程的一大堆API了.在Java5以后,通过Executor来启动线程比用Thread的start()更好.在新特征中 ...
- ExecutorService的submit(Runnable x)和execute(Runnable x) 两个方法的本质区别
Runnable任务没有返回值,而Callable任务有返回值.并且Callable的call()方法只能通过ExecutorService的submit(Callable <T> tas ...
- ExecutorService中submit()和execute()的区别
在使用java.util.concurrent下关于线程池一些类的时候,相信很多人和我一样,总是分不清submit()和execute()的区别,今天从源码方面分析总结一下. 通常,我们通过Execu ...
- 13.ThreadPoolExecutor线程池之submit方法
jdk1.7.0_79 在上一篇<ThreadPoolExecutor线程池原理及其execute方法>中提到了线程池ThreadPoolExecutor的原理以及它的execute方法 ...
- 并发编程(十二)—— Java 线程池 实现原理与源码深度解析 之 submit 方法 (二)
在上一篇<并发编程(十一)—— Java 线程池 实现原理与源码深度解析(一)>中提到了线程池ThreadPoolExecutor的原理以及它的execute方法.这篇文章是接着上一篇文章 ...
随机推荐
- 妙用Outlook2003群发商业邮件
妙用Outlook2003群发商业邮件 我们知道,如果需要在Outlook 2003中向多个对象发送邮件,那么只需要在指定收件人时用分号输入多个邮件地址或者使用抄送方式即可:假如对象较多,可以使用 ...
- Tomcat7安装(linux环境)
1.获取安装包 如果没有tomcat,则创建之,并下载二进制文件到该目录,如下: mkdir /opt/tomcat cd /opt/tomcat wget http://mirrors.hust.e ...
- html5 audio play()方法部分ios机不能播放声音
前几天遇到了一个很奇葩的问题:执行audio.play方法,浏览器.安卓.部分ios可正常播放,部分ios不能播放部分声音,这就奇怪了. 我的第一反应是: 音频文件有问题 -- 写了一个domo验证 ...
- JavaSE中Map框架学习笔记
前言:最近几天都在生病,退烧之后身体虚弱.头疼.在床上躺了几天,什么事情都干不了.接下来这段时间,要好好加快进度才好. 前面用了三篇文章的篇幅学习了Collection框架的相关内容,而Map框架相对 ...
- Echarts报错[MODULE_MISS]"echarts/config" is not exists!
项目用到Echarts插件,时下比较流行的是模块化包引入,但是很悲催的是楼主用的是标签式引入,所以从官网copy来的代码总是报一个 [MODULE_MISS]"echarts/config的 ...
- java三大框架介绍
常听人提起三大框架,关于三大框架,做了如下了解: 三大框架:Struts+Hibernate+Spring java三大框架主要用来做WEN应用. Struts主要负责表示层的显示 Spring利用它 ...
- PHP+NGINX
1. 下载php编译包/nginx编译包(建议先装nginx再装php, php编译包我用的是5.5.35) 2. 创建好安装目录(我的编译包放在/home下) mkdir -p /usr/local ...
- web开发之负载均衡的简单架构
负载均衡 负载均衡的核心思想就是:请求分担 最简单的配置: 一台负载均衡服务器 两台webserver服务器 两台webserver服务器需要配置相同的服务器环境,设置相同的域名指向 负载均衡服务器需 ...
- xdu_1165:均值滤波
题目: Problem A 均值滤波问题描述图像中的噪声在空间上的自相关很低,因此往往可以用均值滤波加以削弱.具体来说,对于每个像素点P(x; y),我们选出所有距P 的Manhattan 距离不超过 ...
- (转)用JUnit4进行单元测试
场景:从开始写代码至今,对于单元测试一直没有重视,但是也厌倦了了程序中的额System.out和log日志输出.单元测试使我看到了在开发过程中的安全性和便捷性,所以下决心好好整理下. 有感而发——&l ...