Open In App

How to Create Thread using Lambda Expressions in Java?

Last Updated : 01 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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();
    }
}


Output

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();
    }
}


Output

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 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
         */
    }
}


Output

Believer track started
GTA-V5 game started
Believer track ended
GTA-V5 game ended


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads