方法引用
public class Main {
public static void main(String[] args) {
//匿名内部类
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("hello world!");
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
需要使用函数式接口的对象的地方可以使用lambda表达式:
public static void main(String[] args) {
//1.
Runnable runnable = () -> {
System.out.println("hello world!");
};
//2.
Thread thread = new Thread(() -> {
System.out.println("hello world!");
});
thread.start();
}
有时已经有现成的方法可以完成你想要传递给其他代码的某个动作,此时可以直接将该方法传递:
public class Main {
public static void main(String[] args) {
//1.
Runnable runnable = Main::myRunnable;
//2.
Thread thread = new Thread(Main::myRunnable);
thread.start();
}
//静态方法
public static void myRunnable() {
System.out.println("hello world!");
}
}
public class Main {
public static void main(String[] args) {
//创建实例
Main main = new Main();
//1.
Runnable runnable = main::myRunnable;
//2.
Thread thread = new Thread(main::myRunnable);
thread.start();
}
//非静态方法
public void myRunnable() {
System.out.println("hello world!");
}
}