如何在 Java 中使用方法引用创建线程?\

java 8object oriented programmingprogramming更新于 2025/4/23 10:22:17

方法引用是 lambda 表达式中引用方法但不执行方法的一种方法。在 lambda 表达式的主体部分,如果另一个方法与函数式接口兼容,我们可以调用它们。我们还可以在方法引用中捕获"this 和"super"关键字。

在下面两个示例中,我们可以使用方法引用借助"this"和"super"关键字创建线程。

此关键字的示例

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

相关文章