Lon*_*yen 7 java lambda multithreading java-8 functional-interface
我得到了这个小代码来测试Callable
.但是,我发现编译器可以知道Lambda是用于Interface 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 );
}
}
Run Code Online (Sandbox Code Playgroud)
Nik*_*las 10
请参阅ExecutorService的文档,其中包含两个submit
带有一个参数的方法:
submit(Callable<T> task)
使用Callable<T>
哪个方法call()
返回T
.submit(Runnable task)
usnig Runnable
有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
});
Run Code Online (Sandbox Code Playgroud)
所以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;
}}
);
Run Code Online (Sandbox Code Playgroud)
要比较,尝试相同,Runnable
你会看到它的方法的返回类型是void
.
executorService.submit(new Runnable() {
@Override
public void run() {
// ...
}}
);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
382 次 |
最近记录: |