ExecutorService的execute和submit方法

更新时间:2023-06-29 19:53:41 阅读: 评论:0

ExecutorService的execute和submit⽅法
因为之前⼀直是⽤的execute⽅法,最近有个情况需要⽤到⽅法,所以研究了下。
三个区别:
1、接收的参数不⼀样
2、submit有返回值,⽽execute没有
Method submit extends ba ute by creating and returning a Future that can be ud 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 ). 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, will rethrow this exception, wrapped in飞瀑流泉
实验室生物安全通用要求an ExecutionException.
意思就是如果你在你的task⾥会抛出checked或者unchecked exception,⽽你⼜希望外⾯的调⽤者能够感知这些exception并做出及时的处理,那么就需要⽤到submit,通过捕获抛出的异常。
⽐如说,我有很多更新各种数据的task,我希望如果其中⼀个task失败,其它的task就不需要执⾏了。那我就需要抛出的异常,然后终⽌其它task的执⾏,代码如下:
星字
1import java.util.ArrayList;
2import java.util.List;
3import java.util.Random;
4import urrent.Callable;
5import urrent.ExecutionException;
6import urrent.ExecutorService;
7import urrent.Executors;
8import urrent.Future;
9
10public class ExecutorServiceTest {
11 public static void main(String[] args) {
12  ExecutorService executorService = wCachedThreadPool();
13  List<Future<String>> resultList = new ArrayList<Future<String>>();
14生硬
15  // 创建10个任务并执⾏
16  for (int i = 0; i < 10; i++) {
17  // 使⽤ExecutorService执⾏Callable类型的任务,并将结果保存在future变量中
18  Future<String> future = executorService.submit(new TaskWithResult(i));
19  // 将任务执⾏结果存储到List中
20  resultList.add(future);
21  }
22  executorService.shutdown();
23
24  // 遍历任务的结果
25  for (Future<String> fs : resultList) {
26  try {
27    System.out.()); // 打印各个线程(任务)执⾏的结果
28  } catch (InterruptedException e) {
29      e.printStackTrace();
30  } catch (ExecutionException e) {
30  } catch (ExecutionException e) {
31    executorService.shutdownNow();
32      e.printStackTrace();
33    return;
34  }
35  }
36 }
颜将军洞省览37}
38
39class TaskWithResult implements Callable<String> {
40 private int id;
41
42 public TaskWithResult(int id) {
43  this.id = id;
44 }
45
46 /**
47  * 任务的具体过程,⼀旦任务传给ExecutorService的submit⽅法,则该⽅法⾃动在⼀个线程上执⾏。
48  *
49  * @return
50  * @throws Exception
51  */
52 public String call() throws Exception {
53  System.out.println("call()⽅法被⾃动调⽤,⼲活            " + Thread.currentThread().getName());
54  if (new Random().nextBoolean())
55  throw new TaskException("Meet error in task." + Thread.currentThread().getName());
56  // ⼀个模拟耗时的操作
57  for (int i = 999999999; i > 0; i--)
58  ;
59  return "call()⽅法被⾃动调⽤,任务的结果是:" + id + "    " + Thread.currentThread().getName();
60 }
61}
62
63class TaskException extends Exception {
64 public TaskException(String message) {
65  super(message);
66 }
67}
执⾏的结果类似于:
员工试用期工作总结1call()⽅法被⾃动调⽤,⼲活            pool-1-thread-1
2call()⽅法被⾃动调⽤,⼲活            pool-1-thread-2
3call()⽅法被⾃动调⽤,⼲活            pool-1-thread-3
4call()⽅法被⾃动调⽤,⼲活            pool-1-thread-5
5call()⽅法被⾃动调⽤,⼲活            pool-1-thread-7游泳的英语怎么写
6call()⽅法被⾃动调⽤,⼲活            pool-1-thread-4
7call()⽅法被⾃动调⽤,⼲活            pool-1-thread-6
8call()⽅法被⾃动调⽤,⼲活            pool-1-thread-7
9call()⽅法被⾃动调⽤,⼲活            pool-1-thread-5
10call()⽅法被⾃动调⽤,⼲活            pool-1-thread-8
11call()⽅法被⾃动调⽤,任务的结果是:0    pool-1-thread-1
12call()⽅法被⾃动调⽤,任务的结果是:1    pool-1-thread-2
urrent.ExecutionException: com.cicc.pts.TaskException: Meet error in task.pool-1-thread-3
14 at urrent.FutureTask$Sync.innerGet(FutureTask.java:222)
15 at (FutureTask.java:83)
16 at com.cicc.pts.ExecutorServiceTest.main(ExecutorServiceTest.java:29)
17Caud by: com.cicc.pts.TaskException: Meet error in task.pool-1-thread-3
18 at com.cicc.pts.TaskWithResult.call(ExecutorServiceTest.java:57)
19 at com.cicc.pts.TaskWithResult.call(ExecutorServiceTest.java:1)
20 at urrent.FutureTask$Sync.innerRun(FutureTask.java:303)
21 at urrent.FutureTask.run(FutureTask.java:138)
22 at urrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
23 at urrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
24 at java.lang.Thread.run(Thread.java:619)
可以看见⼀旦某个task出错,其它的task就停⽌执⾏。

本文发布于:2023-06-29 19:53:41,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/89/1060550.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:任务   结果   需要   失败
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图