2

When you write an anonymous Runnable such as:

Thread producer = new Thread(new Runnable() {
      @Override
      public void run() {
        // do something
      }
});

IntelliJ suggests to replaces it with the following lambda:

Thread producer = new Thread(() -> {
       // do something
    }
});

which works just as fine.

How exactly does this work? In particular:

  1. The constructor used is still Thread(Runnable target), but nothing in the lambda appears to indicate that it's a Runnable.
  2. Why @Override public void run() is suddenly not needed any more?
Sparkler
  • 2,581
  • 1
  • 22
  • 41

1 Answers1

3

If your anonymous class has only one method you can implement it as a lambda expression. What you pass as the lambda here is the implementation of the run method. Lambda expressions let you express instances of single-method classes more compactly.

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63