2

假设:

ExecutorService service = ...;

// somewhere in the code the executorService is used this way:
service.submit(() -> { ... });

lambda 表达式将默认为Callable.
有没有办法让它实例化 a Runnable

谢谢你的帮助。

4

4 回答 4

6

您可以将其声明为 Runnable,或使用强制转换:

Runnable r = () -> { ... };
executorService.submit(r);

或者

executorService.submit((Runnable) () -> { ... });
于 2016-01-08T07:11:00.580 回答
3

你的前提是错误的。此调用不默认为Callable. 选择是通过 lambda 表达式的形状进行的,即它是否返回值:

ExecutorService service = null;

// somewhere in the code the executorService is used this way:

// invokes submit(Runnable)
service.submit(() -> {  });
// invokes submit(Runnable)
service.submit(() -> { return; });
// invokes submit(Callable)
service.submit(() -> "foo");
// invokes submit(Callable)
service.submit(() -> { return "foo"; });

// in case you really need disambiguation: invokes submit(Runnable,null)
service.submit(() -> { throw new RuntimeException(); }, null);
// dito (ignoring the returned value)
service.submit(this::toString, null);

请注意,如果您不需要返回的Future,您可以简单地使用execute(Runnable)直接将 a 加入队列Runnable,而不是将其包装在 a 中FutureTask

于 2016-01-08T13:10:15.347 回答
2
   service.submit((Runnable) () -> {
      ...
   });
于 2016-01-08T07:20:46.180 回答
0

它们的签名之间的区别在于它们Callable返回一个值,而没有。RunnableCallableRunnable

() -> { }一会儿也是如此Runnable,例如() -> ""Callable

于 2017-08-19T11:26:57.010 回答