Lambdas and Runnable



我的理解是Lambda的表达式用于替换抽象实现周围的锅炉代码。 因此,如果我必须创建一个采用可运行接口(功能(的新线程, 我不必创建一个新的匿名类,然后提供void run((,然后在其中编写我的逻辑 相反,可以简单地使用 lambda 并将其指向一个方法,前提是方法签名与 run 相同,即不带任何内容,不返回任何内容。

但是我无法理解下面的实现

Thread t= new Thread(()->printStudent(stud));
public static void printStudent(Student stud) {
System.out.println("Student is "+ stud);
}

在上面的情况下,printStudent 接受一个参数(不像可运行的 run(( 方法(,尽管它以某种方式工作。

这是如何工作的?

以下代码(在类中包装/修改代码(:

public class Main {
public static void main(String[] args) {
String item = "Hello, World!"
Thread t = new Thread(() -> printItem(item));
t.start();
}
public static void printItem(Object item) {
System.out.println(item);
}
}

在功能上等效于:

public class Main {
public static void main(String[] args) {
String item = "Hello, World!"
Thread t = new Thread(new Runnable() {
@Override
public void run() {
printItem(item);
}
});
t.start();
}
public static void printItem(Object item) {
System.out.println(item);
}
}

请注意,在第一个示例中,您必须使用 lambda (->(。但是,您将无法使用方法引用,因为方法printItemRunnable的签名不匹配。这将是非法的:

Thread t = new Thread(Main::printItem);

基本上,方法引用与以下内容相同:

new Runnable() {
@Override
public void run() {
printItem(); // wouldn't compile because the method has parameters
}
}

->后面的表达式或-> {}块中的代码与您放入run()方法中的代码相同。

Runnable singleExpression = () -> /* this is the code inside run()*/;
Runnable codeBlock = () -> {
// this is the code inside run()
};

您没有将参数传递给run()方法,而是表示run()方法的() ->部分。你正在做的只是将方法定义为:

@Override
public void run(){
printStudent(stud); //the value of stud from the context copied here
}

最新更新