Java如何在Lambda中区分Callable和Runnable? [英] How does java differentiate Callable and Runnable in a Lambda?
问题描述
我得到了这个小代码来测试Callable
.但是,我发现这使编译器如何知道Lambda是用于Callable还是Runnable接口,这非常令人困惑,因为它们的函数中都没有任何参数.
I got this little code to test out Callable
. However, I find it pretty confusing how the Compiler could know if the Lambda is for the Interface Callable or Runnable since both don't have any parameter in their function.
但是,IntelliJ显示Lambda将代码用于Callable.
IntelliJ, however, shows that the Lambda employs the code for a Callable.
public class App {
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.submit(() ->{
System.out.println("Starting");
int n = new Random().nextInt(4000);
try {
Thread.sleep(n);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
System.out.println("Finished");
}
return n;
});
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES );
}
}
推荐答案
请参阅ExecutorService的文档,该文档具有2个submit
方法和一个参数:
See the documentation of ExecutorService which has 2 submit
methods with one parameter:
-
Callable<T>
具有方法submit(Runnable task)
usnigRunnable
具有方法run()
不返回任何内容(void
).
submit(Callable<T> task)
usingCallable<T>
which has methodcall()
returningT
.submit(Runnable task)
usnigRunnable
which has methodrun()
returning nothing (void
).
您的lambda输出,返回:
Your lambda gives an output, returns something:
executorService.submit(() -> {
System.out.println("Starting");
int n = new Random().nextInt(4000);
// try-catch-finally omitted
return n; // <-- HERE IT RETURNS N
});
因此lambda必须为Callable<Integer>
,这是以下操作的快捷方式:
So the lambda must be Callable<Integer>
which is a shortcut for:
executorService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("Starting");
int n = new Random().nextInt(4000);
// try-catch-finally omitted
return n;
}}
);
要进行比较,请尝试与Runnable
相同,您会发现该方法的返回类型为void
.
To compare, try the same with Runnable
and you see it's method's return type is void
.
executorService.submit(new Runnable() {
@Override
public void run() {
// ...
}}
);
这篇关于Java如何在Lambda中区分Callable和Runnable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!