如何声明Callable以执行在Java中返回void的函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18512145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to declare Callable to execute function returning void in Java?
提问by Michael
Suppose I would like to run static method foo
asynchronously
假设我想foo
异步运行静态方法
void foo() throws Exception {...}
Since foo
throws an exception I would prefer create a Callable
and invoke ExecutorService.submit
with it to get a Future
.
由于foo
抛出异常,我更喜欢创建一个Callable
并调用ExecutorService.submit
它来获取Future
.
Now I wonder how to declare those Callable
and Future
properly.
Should I declare them
现在我不知道如何申报的Callable
和Future
正确的。我应该宣布他们吗
Callable<Void> and Future<Void>?
采纳答案by Jesper
Should I declare them
Callable<Void>
andFuture<Void>
?
我应该声明他们
Callable<Void>
和Future<Void>
?
Yes.
是的。
Void
is similar to the wrapper classes Integer
, Long
etc. for the primitive types int
, long
etc. You could say it's a wrapper class for void
, even though void
is not really a type.
Void
类似于包装类Integer
,Long
等为基本类型int
,long
等等。你可以说这是一个包装类void
,即使void
不是真正的类型。
回答by emory
I think you should declare them Callable<?>
and Future<?>
. Then you can implement them anyway you want including Callable<Void>
and Future<Void>
.
我认为你应该声明它们Callable<?>
和Future<?>
. 然后你可以以任何你想要的方式实现它们,包括Callable<Void>
和Future<Void>
。