Java中如何使用方法引用创建一个线程

方法引用是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();    //方法引用  
   }
}

输出结果

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();    //方法引用   
    }
}

输出结果

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