如何在 Java 中使用方法引用建立執行緒?\n
方法引用是在 lambda 表示式中引用方法而無需執行其方法的一種方式。在 lambda 表示式的正文部分,如果與功能介面相容,我們可以呼叫其他方法。我們還可以在方法引用中捕獲“this”和“super”關鍵字。
在下面兩個示例中,我們可以使用“this”和“super”關鍵字透過方法引用來建立執行緒。
this 關鍵字示例
public class MethodRefThisTest {
public void runBody() {
for(int i = 1; i < 10; i++) {
System.out.println("Square of " + i + " is: " + (i*i));
}
}
public static void main(String[] args) {
MethodReferenceThread test = new MethodReferenceThread();
test.createThread();
}
private void createThread() {
new Thread(this::runBody).start(); // method reference
}
}輸出
Square of 1 is: 1 Square of 2 is: 4 Square of 3 is: 9 Square of 4 is: 16 Square of 5 is: 25 Square of 6 is: 36 Square of 7 is: 49 Square of 8 is: 64 Square of 9 is: 81
super 關鍵字示例
class SuperReference {
public void runBody() {
for(int i = 1; i < 10; i++) {
System.out.println("Square of " + i +" is: " + (i*i));
}
}
}
public class MethodRefSuperTest extends SuperReference {
public static void main(String[] args) {
MethodRefSuperTest test = new MethodRefSuperTest();
test.createThread();
}
private void createThread() {
new Thread(super::runBody).start(); // method reference
}
}輸出
Square of 1 is: 1 Square of 2 is: 4 Square of 3 is: 9 Square of 4 is: 16 Square of 5 is: 25 Square of 6 is: 36 Square of 7 is: 49 Square of 8 is: 64 Square of 9 is: 81
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP