public class Test {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程:" + Thread.currentThread().getName());
}
});
t.start();
}
}
public class Test {
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread t = new Thread(myThread);
t.start();
}
static class MyThread implements Runnable {
@Override
public void run() {
System.out.println("线程:" + Thread.currentThread().getName());
}
}
}
可以看到使用匿名内部类的话就省略了新建Runnable接口的实现类这一步骤。
3. 使用Lambda表达式
上面使用匿名内部类的写法,如果使用Lambda表达式可以写成下面这样:
public class Test {
public static void main(String[] args) {
Thread t = new Thread(() -> {
System.out.println("线程:" + Thread.currentThread().getName());
});
t.start();
}
}
package com.wangjun.othersOfJava;
public class LambdaTest {
public static void main(String[] args) {
Animal a = () -> { // 编译报错:The target type of this expression must be a functional interface
System.out.println("狗狗吃饭");
};
a.eat();
}
interface Animal {
public void eat();
public void duty();
}
}