Las expresiones Lambda se introducen en Java SE8. Estas expresiones están desarrolladas para interfaces funcionales . Una interfaz funcional es una interfaz con un solo método abstracto. Para saber más sobre las Expresiones Lambda haga clic aquí .
Sintaxis:
(argumento1, argumento2, .. argumento n) -> {
// declaraciones
};
Aquí hacemos uso de la interfaz ejecutable . Como es una interfaz funcional , se pueden usar expresiones lambda. Los siguientes pasos se realizan para lograr la tarea:
- Cree la referencia de la interfaz Runnable y escriba la expresión Lambda para el método run().
- Cree un objeto de clase Thread pasando la referencia creada anteriormente de la interfaz Runnable ya que el método start() está definido en la clase Thread, su objeto necesita ser creado.
- Invoque el método start() para ejecutar el hilo.
Ejemplos
Ejemplo 1:
Java
public class Test { public static void main(String[] args) { // Creating Lambda expression for run() method in // functional interface "Runnable" Runnable myThread = () -> { // Used to set custom name to the current thread Thread.currentThread().setName("myThread"); System.out.println( Thread.currentThread().getName() + " is running"); }; // Instantiating Thread class by passing Runnable // reference to Thread constructor Thread run = new Thread(myThread); // Starting the thread run.start(); } }
myThread is running
Ejemplo 2:
Multithreading-1 usando expresiones lambda
Java
public class Test { public static void main(String[] args) { Runnable basic = () -> { String threadName = Thread.currentThread().getName(); System.out.println("Running common task by " + threadName); }; // Instantiating two thread classes Thread thread1 = new Thread(basic); Thread thread2 = new Thread(basic); // Running two threads for the same task thread1.start(); thread2.start(); } }
Running common task by Thread-1 Running common task by Thread-0
Ejemplo 3:
Multithreading-2 usando expresiones lambda
Java
import java.util.Random; // This is a random player class with two functionalities // playGames and playMusic class RandomPlayer { public void playGame(String gameName) throws InterruptedException { System.out.println(gameName + " game started"); // Assuming game is being played for 500 // milliseconds Thread.sleep(500); // this statement may throw // interrupted exception, so // throws declaration is added System.out.println(gameName + " game ended"); } public void playMusic(String trackName) throws InterruptedException { System.out.println(trackName + " track started"); // Assuming music is being played for 500 // milliseconds Thread.sleep(500); // this statement may throw // interrupted exception, so // throws declaration is added System.out.println(trackName + " track ended"); } } public class Test { // games and tracks arrays which are being used for // picking random items static String[] games = { "COD", "Prince Of Persia", "GTA-V5", "Valorant", "FIFA 22", "Fortnite" }; static String[] tracks = { "Believer", "Cradles", "Taki Taki", "Sorry", "Let Me Love You" }; public static void main(String[] args) { RandomPlayer player = new RandomPlayer(); // Instance of // RandomPlayer to access // its functionalities // Random class for choosing random items from above // arrays Random random = new Random(); // Creating two lambda expressions for runnable // interfaces Runnable gameRunner = () -> { try { player.playGame(games[random.nextInt( games.length)]); // Choosing game track // for playing } catch (InterruptedException e) { e.getMessage(); } }; Runnable musicPlayer = () -> { try { player.playMusic(tracks[random.nextInt( tracks.length)]); // Choosing random // music track for // playing } catch (InterruptedException e) { e.getMessage(); } }; // Instantiating two thread classes with runnable // references Thread game = new Thread(gameRunner); Thread music = new Thread(musicPlayer); // Starting two different threads game.start(); music.start(); /* *Note: As we are dealing with threads output may *differ every single time we run the program */ } }
Believer track started GTA-V5 game started Believer track ended GTA-V5 game ended
Publicación traducida automáticamente
Artículo escrito por mkrishnasai y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA