Java Lambda表达式

93 阅读1分钟

使用场景

接口只有一个方法

使用方法

()->{方法体}
如:Runable p =()->{};//Runable只有run()方法;

用例


import java.text.SimpleDateFormat;
import java.util.Date;

public class LambdaExpression {
    public static void main(String[] args) {

        P t = (a, b) -> {
            for (int i = 0; i < 2; i++) {
                System.out.println("循环中");
            }
            return a + b;
        };
        System.out.println("a+b="+t.func(10,8));

    Runnable R = ()->{
        try
        {
            System.out.println("正在运行的线程名称:R "+new SimpleDateFormat("HH:mm:ss:SSS").format(new Date())+"开始");
            Thread.sleep(4000);    //延时4秒
            System.out.println("正在运行的线程名称:R "+new SimpleDateFormat("HH:mm:ss:SSS").format(new Date())+"结束");
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
    };
    new Thread(R).start();
    new Thread(()-> System.out.println("线程2")).start();
    new Thread(()->{
        try
        {
            System.out.println("正在运行的线程名称:RR "+new SimpleDateFormat("HH:mm:ss:SSS").format(new Date())+"开始");
            Thread.sleep(4000);    //延时4秒
            System.out.println("正在运行的线程名称:RR "+new SimpleDateFormat("HH:mm:ss:SSS").format(new Date())+"结束");
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
    }).start();
}
}
interface P {//P只有一个方法。所以可以用Lambda表达式
    int func(int a,int b);
}