我的理解是Lambda的表达式是用来替换抽象实现周围的锅炉-平台代码的。因此,如果我必须创建一个新的Thread,它需要一个Runnable接口(函数),我不需要创建一个新的匿名类,然后提供void run(),然后在其中编写我的逻辑,而可以简单地使用lambda并将其指向一个方法,只要方法签名与run相同,即不接受任何内容,就不返回任何内容。
然而,我不能理解下面的实现
Thread t= new Thread(()->printStudent(stud));
public static void printStudent(Student stud) {
System.out.println("Student is "+ stud);
}在上面的例子中,printStudent接受一个参数(不像runnable的run()方法),尽管它以某种方式工作。
这是如何工作的?
发布于 2018-09-01 17:49:38
您没有将参数传递给run()方法,而是表示run()方法的() ->部件。您所做的只是将方法定义为:
@Override
public void run(){
printStudent(stud); //the value of stud from the context copied here
}发布于 2018-09-01 17:51:35
以下代码(在类中包装/修改代码):
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 (->)。但是,您不能使用方法引用,因为方法printItem与Runnable的签名不匹配。这将是非法的:
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()
};https://stackoverflow.com/questions/52126810
复制相似问题