从这里answer我了解到 Callable
和 Runnable
之间的唯一区别是前者可以返回执行结果并抛出异常。
我不明白为什么Executor
没有定义采用 Callable
的方法:
void execute(Callable command);
在我看来,为 Runnable
和 Callable
创建方法是合乎逻辑的。在 ExecutorService
,它是 Executor
的子接口(interface),Runnable
和 Callable
都有类似的 submit()
方法。
请解释一下这个设计决定,因为我在 Internet 上找不到任何解释。
最佳答案
I don't understand why
Executor
doesn't define a method which takes aCallable
.
Executor
具有单一职责 - 执行提交的任务。在此抽象级别上,仅使用 Runnable
的 API 不需要 ExecutorService
提出的附加功能。
It'd be logical to create methods for both
Runnable
andCallable
.
是的,因此ExecutorService
接口(interface)是通过扩展Executor
来设计的。 ExecutorService
提供了一个显着的区别 - 提供任务执行的结果。这就是为什么 Callable
、TimeUnit
和生命周期添加了方法。
关于java - 为什么 Executor 接口(interface)没有一个以 Callable 为参数的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47433992/