Java如何在Lambda中区分Callable和Runnable? [英] How does java differentiate Callable and Runnable in a Lambda?

查看:389
本文介绍了Java如何在Lambda中区分Callable和Runnable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了这个小代码来测试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:

  • submit(Callable<T> task) using Callable<T> which has method call() returning T.
  • submit(Runnable task) usnig Runnable which has method run() 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆