Java语法“... =() - > {...}”

时间:2016-04-19 12:51:27

标签: java syntax

最近我看了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!");

  }

}

有人可以指导我查看与此语法相关的文档,或者给我一个适当的解释。

谢谢!

1 个答案:

答案 0 :(得分:4)

这是Java 8 lambdas的语法。实质上:

InitializeComponent

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