繁体   English   中英

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

[英]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方法和一个参数:

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM