简介
Lambda表达式(也称闭包),是Java8发布的新特性中最受期待和欢迎的新特性之一。在Java语法层面Lambda表达式允许函数作为一个方法的参数(函数作为参数传递到方法中),或者把代码看成数据。Lambda表达式用于简化Java中接口式的匿名内部类,被称为函数式接口的概念。函数式接口就是一个只具有一个抽象方法的普通接口,像这样的接口就可以使用Lambda表达式来简化代码的编写。
语法
(args1, args2…)->{};
使用Lambda的条件
对应接口有且只有一个抽象方法
说这么多不如例子来的清楚,我们就以创建线程的例子来对lambda表达式进行简单的说明。先看一下对应的源码:
Thread:(我们取其中一种Constructor来看)
/**
* Allocates a new {@code Thread} object. This constructor has the same
* effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
* {@code (null, target, name)}.
*
* @param target
* the object whose {@code run} method is invoked when this thread
* is started. If {@code null}, this thread's run method is invoked.
*
* @param name
* the name of the new thread
*/
public Thread(Runnable target, String name) {
init(null, target, name, 0);
}
接着我们再来看Runnable的源码:
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
发现刚好符合我们使用Lambda的条件,即有且只有一个抽象方法的接口。那我们接下来就可以使用Lambda来创建一个线程了。
我们先来看一下原始的创建方式(使用匿名内部类):
public static void main(String[] args) {
T t = new T() ;
new Thread(new Runnable() {
@Override
public void run() {
t.m2();
}
},"Thread02").start();
}
接下来看Lambda的形式:
public static void main(String[] args) {
T t = new T();
new Thread(()->t.m1(),"Thread01").start() ;
}
简单的说明一下: ()代表的就是函数式接口中的那个唯一的抽象方法,因为我们重写的这个方法只有一条语句所以可以省略掉{}。如果要重写的方法有参数,只需要在()写入即可,返回值也是一个道理,在{}中写好你的逻辑,最后return 即可;