ADS

Using Lambda Expressions In Threading

 Let us now see how to use lambda expressions in multi threading in Java Using Lambda Expressions in Threading
Let us now see how to use lambda expressions in multi threading in Java. The aim of the Project Lambda in the Java 8 is to make the programmers easy to code the anonymous methods. The following example illustrates using lambda expressions for carrying out multi threading.




class MyLambdaThread

{

    public static void main(String args[])

    {

    // Child thread

    new Thread(() -> {

        for(int i=1;i<=5;i++)

        {

        System.out.println("Child Thread "+i);

            try
      
            {

            Thread.sleep(100);
  
            }catch(Exception e){}

        }

    }).start();

    // Main Thead

        for(int i=1;i<5;i++)

        {

        System.out.println("Main Thread "+i);

            try
      
            {

            Thread.sleep(100);

            }catch(Exception e){}
  
        }

    }

}

Output

 Main Thread 1
Child Thread 1
Main Thread 2
Child Thread 2
Main Thread 3
Child Thread 3
Main Thread 4
Child Thread 4
Child Thread 5

Explaining Lambda Expression

new Thread(() -> {//code}).start(): Here i am using the Thread(Runnable obj) constructor. This constructor takes a Runnable object and the Runnable interface contains only one method that is public void run() which takes no parameters. The body of the thread is written here.

Usually while writing anonymous inner class we write,
 
new Thread(new Runnable(){
       public void run()
       {
       // code
       }
}).start();
Here, while using a lambda expression we can skip new Runnable() and public void run() because the compiler knows that the Thread object takes a Runnable object and that contains only one method that is run() which takes no parameter.

Note: An interface that contains only one abstract method is called as a functional interface.
Ex: ActionListener, Runanble etc.

This is the way in which we can use Java 8 Lambda expressions in Multi threading.
The remaining code however was explained previously in Creating a thread using Runnable

Subscribe to receive free email updates:

ADS