Java 17 Recipes
-6. Implementing Runnable
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
- Bu sahifa navigatsiya:
- How It Works
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 |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling