本文介绍了如何从 Java8 lambda 创建 Runnable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如:

公共类 LambdaTest {私有最终锁锁 = new ReentrantLock();@测试公共无效 createRunnableFromLambda() {Locker.runLocked(lock, () -> {System.out.println("你好世界");});}公共静态类储物柜{public static void runLocked(Lock lock, Runnable block) {锁.锁();尝试 {块运行();} 最后 {锁.解锁();}}}}

所以我的问题是,您能解释一下如何从 lambda 创建 Runnable,并且请有人解释语法 () -> {}.具体来说,() 括号是什么意思?

谢谢.

解决方案

Lambda 可用于任何需要函数式接口的地方.函数式接口是具有单个抽象方法的任何接口.

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

换句话说,() ->System.out.println("hello world"); 在这里是等效的*,其中 Runnable 应该是

 new Runnable(){@覆盖公共无效运行(){System.out.println("世界一号你好!");}};

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

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.

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?

thanks.

解决方案

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.

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.

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

 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 16:45