问题描述
我遇到了一些代码,尽管有点阅读,但我还是很难理解。调用一个方法,该方法接受两个args,其中一个是Runnable。而不是传递一个Runnable对象虽然有一个lambda。
I've come across some code which I'm struggling to understand despite a bit of reading. There is a call to a method which takes in two args, one of which is a Runnable. Rather than passing in a Runnable object though there is a lambda.
例如:
public class LambdaTest {
private final Lock lock = new ReentrantLock();
@Test
public void createRunnableFromLambda() {
Locker.runLocked(lock, () -> {
System.out.println("hello world");
});
}
public static class Locker {
public static void runLocked(Lock lock, Runnable block) {
lock.lock();
try {
block.run();
} finally {
lock.unlock();
}
}
}
}
所以我的问题是,你能解释一下吗?如何从lambda创建Runnable,还有人可以解释语法() - > {}。具体来说,()括号是什么意思?
So my question is, can you explain how a Runnable is created from the lambda, and also please could someone explain the syntax () -> {}. Specifically, what do the () brackets mean?
谢谢。
推荐答案
Lambda可以在任何需要功能接口的地方使用。
功能接口是具有单个抽象方法的任何接口。
A Lambda can be used in any place where a functional interface is required.A functional interface is any interface with a single abstract method.
在这种情况下使用的lambda语法是(参数) - > ; {blockOfCodeOrExpression}
。在单个参数的情况下可以省略括号,并且在单个命令或表达式的情况下可以省略括号。
The lambda syntax used in this case is (arguments) -> {blockOfCodeOrExpression}
. The parenthesis can be omitted in the case of a single argument, and the braces can be omitted in the case of a single command or expression.
换句话说,() - > System.out.println(hello world);
相当于*到
new Runnable(){
@Override
public void run(){
System.out.println("Hello world one!");
}
};
(我很确定它不是字节码等价的,但在功能方面是等价的)
(I'm pretty sure that it is not bytecode-equivalent, but is equivalent in terms of functionality)
这篇关于如何从Java8 lambda创建Runnable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!