どのようにラムダで呼び出し可能とのRunnableを区別するJavaのでしょうか?

ロンググエン:

私がテストするために、この小さなコードを得ましたCallableしかし、私はそれはかなりの両方がその機能で任意のパラメータを持っていないので、ラムダは、インターフェイスコーラブルまたはRunnableのためであればコンパイラが知っている可能性がどのように混乱を見つけます。

ラムダは、呼び出し可能のコードを使用することのIntelliJは、しかし、示しています。

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 );
    }
}
ニコラス:

2つの持っているExecutorServiceののドキュメントを参照してくださいsubmitつのパラメータを持つメソッドを:

あなたのラムダは、出力を与える何かを返します。

executorService.submit(() -> {
    System.out.println("Starting");
    int n = new Random().nextInt(4000);
    // try-catch-finally omitted
    return n;                                      // <-- HERE IT RETURNS N
});

だから、ラムダでなければならない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() {
        // ...  
    }}
);

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=168327&siteId=1