Case parameter as a function of interface methods

Lambda used as parameters and return values

If you put aside to achieve the principle does not say, Java in Lambda expressions may be used as a substitute for anonymous inner classes. If the parameter is a function of process interface type, Lambda expressions can be used instead. Lambda expressions use as a method parameter, in fact, use the function interface as a parameter.

E.g. java.lang.Runnable interface is a function interface, assume that a startThread method using the interface as an argument, it can be used for parameter passing Lambda. In fact, this case and the Thread class constructor parameters Runnable no essential difference.

package com.learn.demo03.LambdaTest;
/*
    例如java.lang.Runnable接口就是一个函数式接口,
    假设有一个startThread方法使用该接口作为参数,那么就可以使用Lambda进行传参。
    这种情况其实和Thread类的构造方法参数为Runnable没有本质区别。
 */
public class Demo01Runnable {
    //定义一个方法startThread,方法的参数使用函数式接口Runnable
    public static void startThread(Runnable run){
        //开启多线程
        new Thread(run).start();
    }

    public static void main(String[] args) {
        //调用startThread方法,方法的参数是一个接口,那么我们可以传递这个接口的匿名内部类
        startThread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"-->"+"线程启动了");
            }
        });

        //调用startThread方法,方法的参数是一个函数式接口,所以可以传递Lambda表达式
        startThread(()->{
            System.out.println(Thread.currentThread().getName()+"-->"+"线程启动了");
        });

        //优化Lambda表达式
        startThread(()->System.out.println(Thread.currentThread().getName()+"-->"+"线程启动
了"));
    }
}

 

Released 2302 original articles · won praise 52 · views 160 000 +

Guess you like

Origin blog.csdn.net/Leon_Jinhai_Sun/article/details/104733697
Recommended