lambda表达式案例
runnable接口
public class RunnableImpl implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 新线程创建了");
}
}
public class Demo01Runnable {
public static void main(String[] args) {
RunnableImpl run = new RunnableImpl();
Thread t = new Thread(run);
t.start();
Runnable r = new Runnable(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 新线程创建了");
}
};
new Thread(r).start();
new Thread(new Runnable(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 新线程创建了");
}
}).start();
}
}
public class Demo02Lambda {
public static void main(String[] args) {
new Thread(new Runnable(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 新线程创建了");
}
}).start();
new Thread(()->{
System.out.println(Thread.currentThread().getName()+" 新线程创建了");
}
).start();
new Thread(()->System.out.println(Thread.currentThread().getName()+" 新线程创建了")).start();
}
}
cook案例
public interface Cook {
public abstract void makeFood();
}
public class Demo01Cook {
public static void main(String[] args) {
invokeCook(new Cook() {
@Override
public void makeFood() {
System.out.println("吃饭了");
}
});
invokeCook(()->{
System.out.println("吃饭了");
});
invokeCook(()-> System.out.println("吃饭了"));
}
public static void invokeCook(Cook cook){
cook.makeFood();
}
}
calculator案例
public interface Calculator {
public abstract int calc(int a,int b);
}
public class Demo01Calculator {
public static void main(String[] args) {
invokeCalc(10, 20, new Calculator() {
@Override
public int calc(int a, int b) {
return a+b;
}
});
invokeCalc(120,130,(int a,int b)->{
return a + b;
});
invokeCalc(120,130,(a,b)-> a + b);
}
public static void invokeCalc(int a,int b,Calculator c){
int sum = c.calc(a,b);
System.out.println(sum);
}
}