ロンググエン:
私がテストするために、この小さなコードを得ました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
つのパラメータを持つメソッドを:
submit(Callable<T> task)
使用Callable<T>
方法持っているcall()
の復帰をT
。submit(Runnable task)
usnigRunnable
方法がありませんrun()
戻って何を(void
)。
あなたのラムダは、出力を与える何かを返します。
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() {
// ...
}}
);