[英]How does java differentiate Callable and Runnable in a Lambda?
我得到了這個小代碼來測試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 );
}
}
請參閱ExecutorService的文檔,其中包含兩個submit
方法和一個參數:
Callable<T>
submit(Callable<T> task)
,其中方法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
});
所以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() {
// ...
}}
);
簽名的主要區別在於Callable
返回值而Runnable
沒有。 所以你的代碼中的這個例子是Callable
,但肯定不是Runnable
,因為它返回一個值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.