假设:
ExecutorService service = ...;
// somewhere in the code the executorService is used this way:
service.submit(() -> { ... });
lambda 表达式将默认为Callable
.
有没有办法让它实例化 a Runnable
?
谢谢你的帮助。
假设:
ExecutorService service = ...;
// somewhere in the code the executorService is used this way:
service.submit(() -> { ... });
lambda 表达式将默认为Callable
.
有没有办法让它实例化 a Runnable
?
谢谢你的帮助。
您可以将其声明为 Runnable,或使用强制转换:
Runnable r = () -> { ... };
executorService.submit(r);
或者
executorService.submit((Runnable) () -> { ... });
你的前提是错误的。此调用不默认为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
。
service.submit((Runnable) () -> {
...
});
它们的签名之间的区别在于它们Callable
返回一个值,而没有。Runnable
Callable
Runnable
() -> { }
一会儿也是如此Runnable
,例如() -> ""
是Callable
。