2 回答

TA貢獻1946條經(jīng)驗 獲得超4個贊
以下代碼(在類中包裝/修改您的代碼):
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);
基本上,方法引用與以下內(nèi)容相同:
new Runnable() {
@Override
public void run() {
printItem(); // wouldn't compile because the method has parameters
}
}
后面的表達式->,或-> {}塊內(nèi)的代碼,與您在run()方法中放置的代碼相同。
Runnable singleExpression = () -> /* this is the code inside run()*/;
Runnable codeBlock = () -> {
// this is the code inside run()
};

TA貢獻1155條經(jīng)驗 獲得超0個贊
您沒有將參數(shù)傳遞給run()方法,它() ->是代表run()方法的部分。你在做什么只是將方法定義為:
@Override
public void run(){
printStudent(stud); //the value of stud from the context copied here
}
添加回答
舉報