Java 17 Recipes


-6. Implementing Runnable


Download 3.2 Mb.
Pdf ko'rish
bet122/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   118   119   120   121   122   123   124   125   ...   245
Bog'liq
Java 17 Recipes

6-6. Implementing Runnable
 Problem
You want to create a runnable piece of code in a terse manner.
 Solution
Utilize a lambda expression to implement the java.util.Runnable interface. The java.
util.Runnable interface is a perfect match for lambda expressions since it contains only 
a single abstract method, run(). This solution compares the legacy technique, creating a 
new Runnable interface, and the new technique using a lambda expression.
The following lines of code demonstrate how to implement a new Runnable piece of 
code using the legacy technique.
public static void main(String[] args) {
Runnable oldRunnable = new Runnable() {
@Override
public void run() {
int x = 5 * 3;
System.out.println("The variable using the old way 
equals: " + x);
}
};
Runnable lambdaRunnable = () -> {
int x = 5 * 3;
ChapTer 6 LaMbda expressIons


226
System.out.println("The variable using the lambda 
equals: " + x);
};
// Calling the runnables
oldRunnable.run();
lambdaRunnable.run();
}
The following is the output.
The variable using the old way equals: 15
The variable using the lambda equals: 15
Now take a look at how this can be written using a lambda expression instead.
Runnable lambdaRunnable = () -> {
int x = 5 * 3;
System.out.println("The variable using the lambda equals: " + x);
};
As you can see, the legacy procedure for implementing a Runnable takes a few more 
lines of code than implementing Runnable with a lambda expression. The lambda 
expression also makes the Runnable implementation easier to read and maintain.
 How It Works
Since java.util.Runnable is a functional interface, the boilerplate of implementing the 
run() method can be abstracted away using a lambda expression. The following is the 
general format for implementing a Runnable with a lambda expression.
Runnable assignment = () -> {expression or statements};
A Runnable interface can be implemented using a zero-argument lambda expression 
containing an expression or a series of statements within the lambda body. The key is 
that the implementation takes zero arguments and returns nothing.
ChapTer 6 LaMbda expressIons


227

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   118   119   120   121   122   123   124   125   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling