本文共 4959 字,大约阅读时间需要 16 分钟。
需求:启动一个线程,在控制台输出一句话 “多线程程序启动了”。
方式一
定义一个类 MyThread 实现 Runnable 接口,重写 run() 方法
public class MyThread implements Runnable { @Override public void run() { System.out.println("多线程程序启动了"); }}
创建 Thread 类的对象,把 MyThread 的对象作为构造参数传递,启动线程
public class Test1 { public static void main(String[] args) { MyThread myThread = new MyThread(); Thread thread = new Thread(myThread); thread.start(); }}
方式二
匿名内部类的方式改进
public class Test2 { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println("多线程程序启动了"); } }).start(); }}
方式三
Lambda 表达式的方式改进
public class Test3 { public static void main(String[] args) { new Thread(() -> { System.out.println("多线程程序启动了"); }).start(); }}
new Thread(new Runnable() { @Override public void run() { System.out.println("多线程程序启动了"); }}).start();
匿名内部类中重写 run() 方法的代码分析:
new Thread(() -> { System.out.println("多线程程序启动了");}).start();
Lambda 表达式的代码分析:
Lambda 表达式的格式:
Lambda 表达式的使用前提:
需求:
实现:
Eatable 接口
public interface Eatable { void eat();}
测试类
public class EatableDemo { private static void useEatable(Eatable e) { e.eat(); } public static void main(String[] args) { useEatable(() -> { System.out.println("I eat an apple"); }); }}
运行结果
I eat an apple
需求:
实现:
Flyable 接口
public interface Flyable { void fly(String s);}
测试类
public class FlyableDemo { private static void useFlyable(Flyable f) { f.fly("I can fly"); } public static void main(String[] args) { useFlyable((String s) -> { System.out.println(s); System.out.println("I am flying"); }); }}
运行结果
I can flyI am flying
需求:
实现:
Addable 接口
public interface Addable { int add(int x, int y);}
测试类
public class AddableDemo { private static void useAddable(Addable a) { int sum = a.add(10, 20); System.out.println(sum); } public static void main(String[] args) { useAddable((int a, int b) -> { return a + b; }); }}
运行结果
30
省略规则:
实例:
Flyable 接口
public interface Flyable { void fly(String s);}
Addable 接口
public interface Addable { int add(int x, int y);}
测试类
public class LambdaDemo { private static void useAddable(Addable a) { int sum = a.add(10, 20); System.out.println(sum); } private static void useFlyable(Flyable f) { f.fly("I can fly"); } public static void main(String[] args) { // 参数类型可以省略(一个参数时) useFlyable((s) -> { System.out.println(s); }); // 参数类型可以省略(多个参数时) useAddable((x, y) -> { return x + y; }); System.out.println("-------------"); // 如果参数有且仅有一个,那么小括号可以省略 useFlyable(s -> { System.out.println(s); }); System.out.println("-------------"); // 如果代码块的语句只有一条,可以省略大括号和分号 useFlyable(s -> System.out.println(s)); // 如果代码块的语句只有一条,可以省略大括号和分号,如果有 return 也要省略掉 useAddable((x, y) -> x + y); }}
运行结果
I can fly30-------------I can fly-------------I can fly30
注意事项:
使用 Lambda 必须要有接口,并且要求接口中有且仅有一个抽象方法
必须有上下文环境,才能推导出 Lambda 对应的接口
根据局部变量的赋值得知 Lambda 对应的接口:
Runnable r = () -> System.out.println("Lambda表达式");
根据调用方法的参数得知 Lambda 对应的接口:
new Thread(() -> System.out.println("Lambda表达式")).start();
所需类型不同
使用限制不同
实现原理不同
转载地址:http://zfjvb.baihongyu.com/