如何声明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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:41:30  来源:igfitidea点击:

How to declare Callable to execute function returning void in Java?

javaconcurrencyfuturecallable

提问by Michael

Suppose I would like to run static method fooasynchronously

假设我想foo异步运行静态方法

void foo() throws Exception {...} 

Since foothrows an exception I would prefer create a Callableand invoke ExecutorService.submitwith it to get a Future.

由于foo抛出异常,我更喜欢创建一个Callable并调用ExecutorService.submit它来获取Future.

Now I wonder how to declare those Callableand Futureproperly. Should I declare them

现在我不知道如何申报的CallableFuture正确的。我应该宣布他们吗

Callable<Void> and Future<Void>?

采纳答案by Jesper

Should I declare them Callable<Void>and Future<Void>?

我应该声明他们Callable<Void>Future<Void>

Yes.

是的。

Voidis similar to the wrapper classes Integer, Longetc. for the primitive types int, longetc. You could say it's a wrapper class for void, even though voidis not really a type.

Void类似于包装类IntegerLong等为基本类型intlong等等。你可以说这是一个包装类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>