One way to create thread is to pass a object that implements Runnable Interface to a Thread constructor as mentioned in Java Multithreading Approaches (Java Concurrency - Part 1): public class MyRunnable implements Runnable{ Java 1.8 introduce Functional Interface. Any interface with a SAM (Single Abstract Method) is a functional interface, and its implementation may be written as a lambda expression. A Functional Interface can have many default methods or static methods declared, but can only have one single abstract method. You may use Lambda Expression in place of a Functional Interface. For example, Runnable interface is a Functional Interface. Let me use the Lambda Expression instead. In this approach, I no longer need to define MyRunnable. public class ThreadDemo{ A method reference is the shorthand/alternative syntax for a lambda expression that executes just ONE method. Replace, () -> printMessage(); with, ThreadDemo::printMessage and get: public class ThreadDemo{ To take the Method Reference syntax one step further, as another example, you can replace Lambda Expression: (p) -> System.out.println(p) with, System.out::println as in: public class MethodReferenceExample{
0 Comments
Leave a Reply. |
Categories
All
Archives
May 2020
|