Java8新特性-Lambda表达式基础

简介
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 即可;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值