如果返回值与我无关,我应该如何在ExecutorService的提交或执行之间做出选择?
如果我对两者都进行测试,除了返回值之外,我没有看到两者之间有任何差异。
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
threadExecutor.execute(new Task());
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
threadExecutor.submit(new Task());
完整的答案是在这里发表的两个答案的组合(加上一点“额外的”):
By submitting a task (vs. executing it) you get back a future which can be used to get the result or cancel the action. You don't have this kind of control when you execute (because its return type id void)
execute expects a Runnable while submit can take either a Runnable or a Callable as an argument (for more info about the difference between the two - see below).
execute bubbles up any unchecked-exceptions right away (it cannot throw checked exceptions!!!), while submit binds any kind of exception to the future that returns as a result, and only when you call future.get() a the (wrapped) exception will be thrown . The Throwable that you'll get is an instance of ExecutionException and if you'll call this object's getCause() it will return the original Throwable.
还有一些(相关的)要点:
即使要提交的任务不需要返回
结果,你仍然可以使用Callable<Void>(而不是使用Runnable)。
可以使用中断机制来取消任务。下面是如何实现取消策略的示例
总而言之,在Callable对象中使用submit(相对于在Runnable对象中使用execute)是一个更好的实践。我将引用Brian Goetz的《Java并发实践》:
6.3.2 Result-bearing tasks: Callable and Future
The Executor framework uses Runnable as its basic task representation. Runnable is a fairly
limiting abstraction; run cannot return a value or throw checked
exceptions, although it can have side effects such as writing to a log
file or placing a result in a shared data structure. Many tasks are
effectively deferred computations—executing a database query, fetching
a resource over the network, or computing a complicated function. For
these types of tasks, Callable is a better abstraction: it expects
that the main entry point, call, will return a value and anticipates
that it might throw an exception.7 Executors includes several utility
methods for wrapping other types of tasks, including Runnable and
java.security.PrivilegedAction, with a Callable.