函数:
需求:启动一个线程,在控制太输出一句话:多线程程序启动了
方式一:
public class Demo {
public static void main(String[] args) {
MyRunnable mr = new MyRunnable();
Thread t = new Thread(mr);
t.start();
}
}
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("多线程程序启动了");
}
}
方式二:
public class Demo {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("多线程程序启动了");
}
}).start();
}
}
方式三:
public class LambdaDemo {
public static void main(String[] args) {
new Thread(() -> {
System.out.println("多线程程序启动了");
}).start();
}
}
匿名内部类中重写run()方法的代码分析
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("多线程程序启动了");
}
}).start();
Lambda表达式的代码分析
new Thread(() -> {
System.out.println("多线程程序启动了");
}).start();
Lambda表达式的三要素:形式参数,箭头,代码块
Lambda表示的格式
Lambda表达式的使用前提:
public interface Eatable {
void eat();
}
public class Demo {
public static void main(String[] args) {
useEatable(() -> {
System.out.println("Hello,World");
});
}
private static void useEatable(Eatable e){
e.eat();
}
}
public interface Flyable {
void fly(String s);
}
public class Demo {
public static void main(String[] args) {
//匿名内部类:
useFlyable(new Flyable() {
@Override
public void fly(String s) {
System.out.println(s);
System.out.println("风和日丽");
}
});
System.out.println("---------------");
//Lambda表达式
useFlyable((String s) -> {
System.out.println(s);
System.out.println("风和日丽");
});
}
private static void useFlyable(Flyable f){
f.fly("晴空万里");
}
}
public interface Addable {
int add(int x, int y);
}
public class Demo {
public static void main(String[] args) {
//匿名内部类
useAddable(new Addable() {
@Override
public int add(int x, int y) {
return x + y;
}
});
System.out.println("------------");
//Lambda表达式
useAddable((int x, int y) -> {
return x + y;
});
}
private static void useAddable(Addable a) {
int sum = a.add(3, 4);
System.out.println(sum);
}
}
public class Demo {
public static void main(String[] args) {
//无省略
useAddable((int x, int y) -> {
return x + y;
});
useFlyable((String s) -> {
System.out.println(s);
});
System.out.println("------------");
//参数类型省略
useAddable((x, y) -> {
return x + y;
});
useFlyable(s -> {
System.out.println(s);
});
System.out.println("----------------");
//若代码块有且只有一条语句,可以省略大括号和分号,若有return语句也要省略return;
useAddable((x, y) -> x + y);
useFlyable(s -> System.out.println(s));
}
private static void useAddable(Addable a) {
int sum = a.add(10, 30);
System.out.println(sum);
}
private static void useFlyable(Flyable f) {
f.fly("阳光明媚,风和日丽");
}
}
原文:https://www.cnblogs.com/Hz-z/p/13052347.html