说一说ExecutorService.submit()与Executor.execute() 两个方法的相同与不同之处
相同之处:
- Both submit() and execute() methods are used to submit a task to Executor framework for asynchronous execution.
submit和execute方法均可以想线程池中提交一个任务,让线程池来异步执行这个任务 - Both submit() and execute() can accept a Runnable task.
两个方法均可以接受Runnable类型的任务 - 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接口中定义的
不同之处:
- The submit() can accept both Runnable and Callable task but execute() can only accept the Runnable task.
submit方法既能接受有返回结果Callable类型和没有返回结果的Runnable类型,而execute方法只能结构没有返回结果的Runnable类型 - The submit() method is declared in ExecutorService interface while execute() method is declared in the Executor interface.
submit方法是定义在ExecutorService接口中的,而execute方法是定义在Executor接口中的 - The return type of submit() method is a Future object but return type of execute() method is void.
submit方法的返回值是一个Future,而execute方法的返回值是void - 对于异常的处理
使用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