如何从 Java8 lambda 创建 Runnable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34026903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:15:08  来源:igfitidea点击:

How Runnable is created from Java8 lambda

javalambdajava-8

提问by robjwilkins

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.

我遇到了一些代码,尽管阅读了一些,但我仍然难以理解。有一个方法调用,它接受两个参数,其中一个是 Runnable。尽管有一个 lambda,而不是传入一个 Runnable 对象。

For example:

例如:

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();
            }
        }
    }
}

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 创建 Runnable 吗,也请有人解释一下语法()-> {}。具体来说,() 括号是什么意思?

thanks.

谢谢。

采纳答案by Pedro Affonso

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 可用于任何需要功能接口的地方。函数式接口是具有单个抽象方法的任何接口。

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.

在这种情况下使用的 lambda 语法是(arguments) -> {blockOfCodeOrExpression}. 在单个参数的情况下可以省略括号,在单个命令或表达式的情况下可以省略大括号。

In other words, () -> System.out.println("hello world");is equivalent* here where a Runnableis expected to

换句话说,() -> System.out.println("hello world");这里是等价的*,其中 aRunnable预期为

 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)

*(我很确定它不是字节码等价的,但在功能方面是等价的)