How to create a thread using method reference in Java?


Method reference is one of a way in a lambda expression to refer a method without executing it. In the body part of a lambda expression, we can call another method if they are compatible with a functional interface. We can also capture "this" and "super" keywords in method references.

In the below two examples, we can create a thread with the help of "this" and "super" keywords using method reference.

Example of this keyword

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
   }
}

Output

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

Example of super keyword

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
   }
}

Output

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

Updated on: 14-Jul-2020

519 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements