假设:
ExecutorService service = ...;
// somewhere in the code the executorService is used this way:
service.submit(() -> { ... });
lambda表达式默认为Callable
。
有没有办法让它实例化Runnable
?
感谢您的帮助。
答案 0 :(得分:6)
您可以将其声明为Runnable,或使用强制转换:
Runnable r = () -> { ... };
executorService.submit(r);
或
executorService.submit((Runnable) () -> { ... });
答案 1 :(得分: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)
直接将Runnable
入队,而不是将其包裹在{{1}中}}
答案 2 :(得分:2)
service.submit((Runnable) () -> {
...
});
答案 3 :(得分:0)
Callable
和Runnable
在签名方面的区别在于Callable
正在返回一个值,而Runnable
却没有。
所以() -> { }
是Runnable
,例如() -> ""
是Callable
。