In this article, I'm going to explain the way we can use lambda to implement the Runnable interface.
General scenario is below:
Note: Runable interface only one method callrun ( ), so we can write lambda expression. If there is more than one method declaration inside a interface, we cannot write lambda expression.
Enjoy..!!
General scenario is below:
...
Thread myThread = new Thread( new Runnable( ) {
@Override
public void run( ) {
System. out. println ( "Printed inside runnable");
System. out. println ( Thread. currentThread ( ). getId ( ));
}
} );
myThread . start( );
...
Below is the code segment, same above implementation with lambda. ...
Thread myLambdaThread = new Thread( () -> {
System. out. println ( "printed inside the lambda expression");
System. out. println ( "Thread Id: " + Thread. currentThread ( ). getId ( ));
} );
myLambdaThread . start( );
...
- Empty parentheses: because
run ( ) method doesn't allow any arguments. - If there is more than one line of the implementation, we need to write the implementation inside the curly brackets.
Note: Runable interface only one method call
Enjoy..!!
No comments:
Post a Comment