ExecutorService的execute和submit方法

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告诉我它的执行结果,是成功还是失败,如果是失败,原因是什么。然后我就可以把所有失败的原因综合起来发给调用者。并且Callable的call()方法只能通过ExecutorService的submit(Callable<T> task) 方法来执行。

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的执行。

注解解释

 

Java code?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

public class RunnableTestMain {

 

    public static void main(String[] args) {

        ExecutorService pool = Executors.newFixedThreadPool(2);

         

        /**

         * execute(Runnable x) 没有返回值。可以执行任务,但无法判断任务是否成功完成。

         */

        pool.execute(new RunnableTest("Task1")); 

         

        /**

         * submit(Runnable x) 返回一个future。可以用这个future来判断任务是否成功完成。请看下面:

         */

        Future future = pool.submit(new RunnableTest("Task2"));

         

        try {

            if(future.get()==null){//如果Future's get返回null,任务完成

                System.out.println("任务完成");

            }

        catch (InterruptedException e) {

        catch (ExecutionException e) {

            //否则我们可以看看任务失败的原因是什么

            System.out.println(e.getCause().getMessage());

        }

 

    }

 

}

 

public class RunnableTest implements Runnable {

     

    private String taskName;

     

    public RunnableTest(final String taskName) {

        this.taskName = taskName;

    }

 

    @Override

    public void run() {

        System.out.println("Inside "+taskName);

        throw new RuntimeException("RuntimeException from inside " + taskName);

    }

 

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值