ExecutorService.submit()与Executor.execute() 两个方法的相同与不同之处

说一说ExecutorService.submit()与Executor.execute() 两个方法的相同与不同之处

相同之处:
  1. Both submit() and execute() methods are used to submit a task to Executor framework for asynchronous execution.
    submit和execute方法均可以想线程池中提交一个任务,让线程池来异步执行这个任务
  2. Both submit() and execute() can accept a Runnable task.
    两个方法均可以接受Runnable类型的任务
  3. You can access submit() and execute() from the ExecutorService interface because it also extends the Executor interface which declares the execute() method.
    从ExecutorService接口中均可以调用submit和execute方法,但是submit方法是在ExecutorService接口中定义的,而execute方法是在Executor接口中定义的
不同之处:
  1. The submit() can accept both Runnable and Callable task but execute() can only accept the Runnable task.
    submit方法既能接受有返回结果Callable类型和没有返回结果的Runnable类型,而execute方法只能结构没有返回结果的Runnable类型
  2. The submit() method is declared in ExecutorService interface while execute() method is declared in the Executor interface.
    submit方法是定义在ExecutorService接口中的,而execute方法是定义在Executor接口中的
  3. The return type of submit() method is a Future object but return type of execute() method is void.
    submit方法的返回值是一个Future,而execute方法的返回值是void
  4. 对于异常的处理
    使用submit方式提交的任务若在执行的过程中抛出了异常的话,异常信息会被吃掉(在控制台中看不到),需要通过Future.get方法来获取这个异常;使用execute方式提交的任务若在执行的过程中出现异常的话,异常信息会被打印到控制台
ExecutorService executorService = Executors.newFixedThreadPool(50);

Future<?> future = executorService.submit(() -> {
    System.out.println("submit提交抛出异常的任务");
    try {
        Thread.sleep(3_000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    // 虽然这里出现了异常,但是在控制台不会打印出
    int i = 1 / 0;
});
try {
    // 通过submit提交的任务,如果出现异常的话,可以通过Future.get方法获取到
    System.out.println("submit runnable task and get result: " + future.get());
} catch (ExecutionException ee) {
    System.out.println("1111" + ee);
} catch (InterruptedException ie) {
    System.out.println("2222" + ie);
}

// 通过execute提交的任务,若果任务在执行的过程中出现异常的话,异常的信息将直接被打印出
executorService.execute(() -> {
    System.out.println("execute提交抛出异常的任务");
    try {
        Thread.sleep(4_000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    // 这里出现异常后,会直接在控制台打印出
    int i = 1 / 0;
});

网上有人说通过submit或者execute提交的任务,若一个任务失败的话,其他的任务就停止执行了,这种说法是错误的

什么时候使用这两个方法:

若需要获取异步执行任务的返回值的话,使用submit方法;若仅仅是让一个任务在线程池中异步执行,使用execute方法

参考:https://javarevisited.blogspot.com/2016/04/difference-between-ExecutorServie-submit-vs-Executor-execute-method-in-Java.html

  • 8
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值