Lambda Expressions are introduced in Java SE8. These expressions are developed for Functional Interfaces. A functional interface is an interface with only one abstract method. To know more about Lambda Expressions click here.
Syntax:
(argument1, argument2, .. argument n) -> {
// statements
};
Here we make use of the Runnable Interface. As it is a Functional Interface, Lambda expressions can be used. The following steps are performed to achieve the task:
- Create the Runnable interface reference and write the Lambda expression for the run() method.
- Create a Thread class object passing the above-created reference of the Runnable interface since the start() method is defined in the Thread class its object needs to be created.
- Invoke the start() method to run the thread.
Examples
Example 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
Example 2:Â
Multithreading-1 using lambda expressions
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
Example 3:Â
Multithreading-2 using lambda expressions
Java
import java.util.Random;Â
// This is a random player class with two functionalities// playGames and playMusicclass 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
