某接口,只有一个方法。
比如这个:
package java.lang; @FunctionalInterface public interface Runnable { void run(); }
或者是这个:
interface MyInterface{ void sayHi(); }
一般我们要使用Runable子类开启一个线程,要实现Runnable接口,调用Threead类的start方法:
public class LeaningLamda implements Runnable{ public static void main(String[] args) { new Thread(new LeaningLamda()).start(); } @Override public void run() { System.out.println(this.getClass()+"我已经在跑了!"); } 或者用sayHi方法干点什么,要先实现接口,再调用:
public class LeaningLamda2 implements MyInterface{ public static void main(String[] args) { new LeaningLamda2().sayHi(); } @Override public void sayHi() { System.out.println("ok ok ok ok ,i am say Hi!"); } } interface MyInterface{ void sayHi(); }
如果这个方法我就用一次,那我可以在内部类中实现它,提高程序性能:
public class LeaningLamda{ static class MyRun implements Runnable{ @Override public void run() { System.out.println(this.getClass()+"我已经在跑了!"); } } public static void main(String[] args) { new Thread(new MyRun()).start(); } }
public class LeaningLamda2 {
static class MyHi implements MyInterface{ @Override public void sayHi() { System.out.println("ok ok ok ok ,i am say Hi!"); } } public static void main(String[] args) { new MyHi().sayHi(); } } interface MyInterface{ void sayHi(); }
既然只使用一次,那我为啥不把它放在使用的方法里面去,性能不就又UpUpUpUp。
像这样:
public class LeaningLamda{ public static void main(String[] args) { class MyRun implements Runnable{ @Override public void run() { System.out.println(this.getClass()+"我已经在跑了!"); } } //调用在定义后面,谢谢。 new Thread(new MyRun()).start(); } }
public class LeaningLamda2 { public static void main(String[] args) { class MyHi implements MyInterface{ @Override public void sayHi() { System.out.println("ok ok ok ok ,i am say Hi!"); } } new MyHi().sayHi(); } } interface MyInterface{ void sayHi(); }
我就用一次,要什么名字啊?能少输入一个字符都是赚的。需要借助父类或者接口名来实现。
public class LeaningLamda{ public static void main(String[] args) { //需要借助父类或者接口来声明 new Thread(new Runnable(){ @Override public void run() { System.out.println(this.getClass()+"我已经在跑了!"); } }).start(); } }
public class LeaningLamda2 { public static void main(String[] args) { new MyInterface(){ @Override public void sayHi() { System.out.println("ok ok ok ok ,i am say Hi!"); } }.sayHi(); } } interface MyInterface{ void sayHi(); }
jdk 8 看不下去了,给我们提供了一个更加简化的方案,你看:
lamda表达式实现创建单个简单线程:
public class LeaningLamda{ public static void main(String[] args) { new Thread(()-> { System.out.println("我已经在跑了!"); } ).start(); } }
lamda表达式sayHi:
public class LeaningLamda2 { public static void main(String[] args) { //此处需要借助一个父类或接口对象来存放,调用它 MyInterface ls = ()->{ System.out.println("ok ok ok ok ,i am say Hi!"); }; ls.sayHi(); } } interface MyInterface{ void sayHi(); }