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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章