Lambda Thread Creation Example

Lambda Thread Creation Example

In JDK 8 introduced Lambda expression to address bulkiness of multiple lines of codes into single lines to solve vertical problem of inner class. Lambda expression consists of three parts:

Argument ListArrow tokenBody
(int y, int z)->y+z

Below I will show you how to write Runnable using Lambda:

  • LambdaAnonymousThreadCreation.java:
public class LambdaAnonymousThreadCreation {

	public static void main(String[] args) {
		
		System.out.println("Main thread name: " +Thread.currentThread().getName());
		
		//Anonymous class thread creation
		Runnable runnable = new Runnable() {
			
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName()+" Old way running");				
			} 	
		};
		
		Thread thread = new Thread(runnable);
		thread.start();
		
		//Replaced by Lambda		
		Runnable runnable2 = ()-> {System.out.println(Thread.currentThread().getName()+" Lambda migration thread running");};
		thread = new Thread(runnable2);
		thread.start();
		
		
		oldWayThreadCreation();
		lambdaThreadCreation();

	}
	
	public static void oldWayThreadCreation() {
		
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("Old way of thread creation");
				System.out.println(Thread.currentThread().getName()+" Old way running");
				
			}
		});
		
		thread.start();
		
	}
	
	public static void lambdaThreadCreation() {
		
		Thread thread = new Thread(()->{
			System.out.println("Lambda migration of thread creation");
			System.out.println(Thread.currentThread().getName()+" Lambda migration thread running");
			
		});
		
		thread.start();
		
	}

}
  • Output:

Lambda Thread Creation Example

  • For more information please visit Oracle documentation here

Leave a Reply

Your email address will not be published. Required fields are marked *