java - java如何区分Lambda中的Callable和Runnable?
问题描述
我得到了这个小代码来测试Callable
。但是,我发现编译器如何知道 Lambda 是用于接口 Callable 还是 Runnable 非常令人困惑,因为它们的函数中都没有任何参数。
然而,IntelliJ 显示 Lambda 使用 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
方法和一个参数:
submit(Callable<T> task)
使用Callable<T>
which 有方法call()
返回T
。submit(Runnable task)
usnigRunnable
的方法run()
不返回任何内容 (void
)。
你的 lambda 给出一个输出,返回一些东西:
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>
是以下的快捷方式:
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
.
executorService.submit(new Runnable() {
@Override
public void run() {
// ...
}}
);
推荐阅读
- apache2.4 - Catalina apache 2.4.41 http://localhost/~username 在此服务器上找不到请求的 URL
- c++ - Shared_ptr 自定义删除器
- java - 收到错误 java.lang.NoSuchFieldError: pBuffers
- c# - 如何将用户分配到 Azure 资源组
- r - 通过R中的属性提取sf对象中的点
- c# - Godot Sentry 崩溃报告
- javascript - 来自 http 409 的 Ajax 解析响应
- ios - 使用 iOS 锁定屏幕上的播放器控件进行远程控制应用程序
- ascii - 如何在 PyCharm 中打印此符号:“█”
- git - 如何使用 git 从提交或拉取请求中提取文件路径和更改?