This question already has answers here:
What is the breakdown for Java's lambda syntax?
                                
                                    (4个答案)
                                
                        
                4年前关闭。
            
        

最近,我在看http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/教程,他使用以下语法。

Runnable task = () -> {
    String threadName = Thread.currentThread().getName();
    System.out.println("Hello " + threadName);
};

task.run();

Thread thread = new Thread(task);
thread.start();

System.out.println("Done!");


我推断出可以使用以下方式创建类,而不是使用我不完全理解(没有找到与此语法相关的任何文档)的“ ... =->(){...}”。

public class IAmRunnable1 implements Runnable {

  @Override
  public void run() {
    String threadName = Thread.currentThread().getName();
    System.out.println("Hello " + threadName);

  }

}


并在我的代码中使用此类,如下所示:

//ref:http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/
public class ExecutorRunnableExample {

  public static void main(String[] args) {

    Runnable task = new IAmRunnable1();

  task.run();

  Thread thread = new Thread(task);
  thread.start();

  System.out.println("Done!");

  }

}


有人可以将我定向到与此语法相关的文档,或者给我适当的解释。

谢谢!

最佳答案

这是Java 8 lambda的语法。在本质上:

Runnable r = () -> { ... }


是相同的

Runnable r = new Runnable() { public void run() {  ... } }

关于java - Java语法“…=()-> {…}” ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36718975/

10-11 22:32
查看更多