应该优先于Runnable吗? [英] Shall Callable be preferred over Runnable?
问题描述
我已经了解了Java中的 Runnable
和 Callable
接口之间的区别。从Java 1.5开始,已经向 Runnable
接口添加了附加功能,并且为了保持向后兼容性,已经调用了 Callable
。
I have understood the difference between Runnable
and Callable
interface in Java. From Java 1.5 additional features has been added to Runnable
interface and has been called Callable
in order to maintain backward compatibility.
我的问题是,我们有 Callable
接口,我们总是使用它吗?不使用 Callable
并使用 Runnable
的用例是什么?
My questions is now that we have Callable
interface, shall we always use that? What are the use cases of not using Callable
and using Runnable
?
(This is a good article on what are the differences between them)
推荐答案
,并且都由java.util.concurrent中的Executor框架支持。 Runnable已经有更长的时间,但它仍在使用中,并且不鼓励。
Both have their uses, and both are supported by the Executor framework in java.util.concurrent. Runnable has been around longer, but it is still in use and not discouraged.
Callables可以抛出异常和返回值,这使它们成为更好的抽象结果轴承任务(例如从网络获取资源,执行昂贵的值计算等)[来自Goetz,Bloch等人的实践中的Java并发实践]。 al。,Java并发的标准工作]。
Callables can throw exceptions and return values, which makes them the better abstraction for result-bearing tasks (such as fetching a resource from the network, performing an expensive computation of a value, and the like) [from Java Concurrency in Practice by Goetz, Bloch et. al., the standard work on Java concurrency].
所以,如果你在设计一个API,我建议尽可能使用Callables。如果你确定任务不会返回值,并且不会抛出异常,那么Runnables也是一个有效的选择。这里没有黑色和白色,特别是因为Runnables可以很容易地包装在Callables中,反之亦然。
So, if you are designing an API, I would suggest using Callables when possible. If you are sure that the tasks will not return values and will not throw exceptions, then Runnables are also a valid choice. There is no black and white here, especially because Runnables can easily be wrapped in Callables and vice versa.
注意,你的Callable实现不需要声明 throws Exception
; Callable自己声明它只允许实现器抛出任何检查的异常。您的Callable的Caller只依靠Callable接口将不得不编写异常处理代码。
另外请注意,Callables不需要返回值;您可以简单地声明您的Callable以返回 Void
(资本为 V
')。
As an aside, note that your Callable implementation need not declare throws Exception
; the fact that Callable itself declares it is only to allow implementors to throw any checked exceptions. Callers of your Callable who rely solely on the Callable interface will have to write exception handling code, though.
Also note that Callables need not return a value; you can simply declare your Callable to return Void
(with capital 'V
').
这篇关于应该优先于Runnable吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!