package practice15; public class LambdaDemo { public static void main(String[] args) { //实现类的方式实现需求 MyRunnable my = new MyRunnable(); Thread t = new Thread(my); t.start(); //匿名内部类的方式改进 new Thread(new Runnable() { @Override public void run() { System.out.println("多线程程序启动了"); } }).start(); //Lambda表达式的方式改进 new Thread(()->{ System.out.println("多线程程序启动了"); }).start(); } } class MyRunnable implements Runnable{ @Override public void run() { System.out.println("多线程程序启动了"); } }
package practice15; 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(); } } interface Eatable { void eat(); } class EatableImpl implements Eatable{ @Override public void eat() { System.out.println("我喜欢吃鱼"); } }
interface Flyable { void fly(String s); } public class FlyableDemo { public static void main(String[] args) { //匿名内部类 useFlyable(new Flyable() { @Override public void fly(String s) { System.out.println(s); System.out.println("飞机自驾游"); } }); //Lambda useFlyable((String s)->{ System.out.println(s); System.out.println("汽车自驾游"); }); } private static void useFlyable(Flyable f) { f.fly("风和日丽,晴空万里"); } }
interface Addable { int add(int x,int y); } public class AddableDemo { public static void main(String[] args) { useAddable((int x,int y)->{ return x+y; }); } private static void useAddable(Addable a) { int sum = a.add(10,20); System.out.println(sum); } }
interface Flyable { void fly(String s); } public interface Addable { int add(int x,int y); } public class LambdaDemo { public static void main(String[] args) { useAddable((int x,int y)->{ return x+y; }); //参数的类型可以省略 useAddable((x, y)->{ return x+y; }); //有多个参数的情况下,不能只省略一个 useFlyable((s)->{ System.out.println(s); }); //如果参数有且只有一个,那么小括号可以省略 useFlyable(s->{ System.out.println(s); }); //如果代码块的语句只有一条,可以省略大括号和分号,如果有return,也可以省略 useFlyable(s-> System.out.println(s)); useAddable((x,y)->x+y); } private static void useFlyable(Flyable f) { f.fly("风和日丽,晴空万里"); } private static void useAddable(Addable a) { int sum = a.add(10,20); System.out.println(sum); } }
interface Inter { void show(); // void method(); } public class LambdaDemo { public static void main(String[] args) { //使用Lambda必须要有接口,并且要求接口有且仅有一个抽象方法 useInter(() -> System.out.println("好好学习,天天向上")); //必须有上下文环境,才能推到出Lambda对应的接口 new Thread(new Runnable() { @Override public void run() { System.out.println("匿名内部类"); } }).start(); // ()-> System.out.println("Lambda表达式"); 报错 Runnable r = ()-> System.out.println("Lambda表达式"); new Thread(r).start(); new Thread(()-> System.out.println("Lambda表达式")).start(); } private static void useInter(Inter i) { i.show(); } }