java如何区分Lambda中的Callable和Runnable?

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带有一个参数的方法:

你的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)