Java 8 Threads with Lambdas

Author: Brian Nettles | Date Created: May 21, 2018 | Visits: 162


Java 8 gave developers some new syntax known as lambdas. The great benefit of Lambdas is that they are less verbose. Less verbose means simpler code. But although the code may be simpler, if you don't know the new syntax, it is there only to confuse.

Lambas give shortcuts to simple one method classes. A basic example of a one method class would be both the Thread class and its counterpart, the Runnable interface. Both include the "run" method.

I have given a snippet of code that is marked up with comments to help you better understand what is going on here.

public class ThreadExample {

	public ThreadExample() {
		System.out.println("ThreadExample Started");

		// Traditional way.
		// MyThread class is defined below as an inner class which extends Thread.
		MyThread myThread = this.new MyThread();
		myThread.start();
		
		// Traditional way.
		// MyRunnable is defined below as an implementation 
		// of an inner class implementing the Runnable interface.		
		new Thread(this.new MyRunnable()).start();
		
		// create a Runnable lambda generated class
		// notice no need to create the run method
		// () represents instantiation of Runnable object and automatic invocation of run method
		// -> { }  put all code of the implied run method in your curly braces.
		Runnable runner = () -> {
			for(int i=0;i<10000; i++) {
			    System.out.println("Runnable Runner " + i);
			}
		};
		new Thread(runner).start();
		
		// No need to create the runnable object.  
		// Just insert the code where the Runnable interface would have gone.
		// A lot is accepted by the lambda usage as implied.
		// () represents instantiation of Runnable object and automatic invocation of run method
		// -> { }  put all code of the implied run method in your curly braces.
		new Thread(() ->  {
			for(int i=0;i<10000; i++) {
			    System.out.println("Anonymous Lambda " + i);
			}	
		}).start();
	}
	
	public static void main(String[] args) {
		new ThreadExample();
	}
	
	class MyRunnable implements Runnable {
	    
		@Override
		public void run() {
			for(int i=0;i<10000; i++) {
			    System.out.println("MyRunnable " + i);
			}
		}
	}
	
	class MyThread extends Thread {
	
		@Override
		public void run() {
			for(int i=0;i<10000; i++) {
			    System.out.println("MyThread " + i);
			}
		}
	}
}

If for no other reason than to benefit myself, this page is created for those who need a simple reminder of how to create threads in Java 8 using Lambda expressions.

 
Trisummit Technologies
6421 N. Lena Place
Tucson, AZ 85741
575-322-6697
© 2018 All Rights Reserved