如何在 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