文章目录

函数式接口定义:
所谓函数式接口,指的是只有一个抽象方法的接口。
函数式接口可以被隐式转换为Lambda表达式。
函数式接口可以用@FunctionalInterface注解标识。
举个例子
1 2 3 4 5 6 |
@FunctionalInterface interface GreetingService { void sayMessage(String message); } |
那么就可以使用Lambda表达式来表示该接口的一个实现(注:JAVA 8 之前一般是用匿名类实现的):
1 2 |
GreetingService greetService1 = message -> System.out.println("Hello " + message); |
多线程中的 Runnable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@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 表达式 方式调用多线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public class StartThread3{ public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println("hello world"); } }).start(); } } # 匿名函数 new Runnable() { @Override public void run() { System.out.println("hello world");}} public class StartThread3{ public static void main(String[] args) { new Thread(()->{System.out.println("hello world")}).start(); } } # lambda 表达式 ()->{System.out.println("hello world")} |
Lambda 中如果有参数
如果有参数
1 2 |
(String a)->{System.out.println("hello world"+a)} |
也可以 不写类型
1 2 |
(a)->{System.out.println("hello world"+a)} |
