需求:启动一个线程,在控制台输出一句话:多线程启动了
代码演示:
public class LambdaDemo {
public static void main(String[] args) {
//匿名内部类改进
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("多线程程序启动了");
}
}).start();
//lambda表达式改进
new Thread(() -> {
System.out.println("多线程程序启动了");
}).start();
}
}
Lambda表达式的使用前提
代码实现:
定义一个接口(Eatable)
package TEMP.TEMP30;
public interface Eatable {
void eat();
}
定义接口的实现类:
public class EatableImpl implements Eatable {
@Override
public void eat() {
System.out.println("吃苹果");
}
}
定义测试类:
public class EatableDemo {
public static void main(String[] args) {
//在主方法中调用useEatable()方法
Eatable e = new EatableImpl();
useEatable(e);
//匿名内部类改进
useEatable(new Eatable() {
@Override
public void eat() {
System.out.println("吃苹果");
}
});
//lambda表达式改进
useEatable(() -> {
System.out.println("吃苹果");
});
}
private static void useEatable(Eatable e) {
e.eat();
}
}
定义接口:
public interface Flyable {
void fly(String s);
}
定义接口实现类:
public class FlyableImpl implements Flyable {
@Override
public void fly(String s) {
System.out.println(s + "飞起来了");
}
}
定义测试类:
public class FlyableDemo {
public static void main(String[] args) {
//调用useFlyable方法
Flyable f = new FlyableImpl();
useFlyable(f, "狗");
//匿名内部类
useFlyable(new Flyable() {
@Override
public void fly(String s) {
System.out.println(s + "飞起来了");
}
}, "猫");
//lambda表达式改进
useFlyable((String s) -> {
System.out.println(s + "飞起来了");
}, "鱼");
}
private static void useFlyable(Flyable f, String s) {
f.fly(s);
}
}
定义接口:
public interface Addable {
int add(int x,int y);
}
定义测试类:
public class AddableDemo {
public static void main(String[] args) {
//lambda方法
useAddable((int x, int y) -> {
return x + y;
});
}
private static void useAddable(Addable a) {
int sum = a.add(10, 20);
System.out.println(sum);
}
}
省略规则:
注意事项: