How to create threads using lambda expressions

When we create a thread we either extend the Thread class or create an object to pass in to the Thread class constructor that implement the Runnable interface. This example shows how to implements the Runnable interface by declaring anonymous classes and pass them to the Thread constructor using lambda expressions.

If you’re using a Java version that is < 8, you will instead want to look at this example: How to create a thread

This code example below shows three different threads created with three anonymous classes implementing the Runnable interface. The Runnable interface is a so called FunctionalInterface which means that it has exactly one abstract method. In this case the method name is run() and takes no parameters. That is the method called when the thread’s start() method is executed.

The lambda expression can be used by either specifying an expression, several statements within curly brackets, or just a single statement without curly brackets. In the code below there are examples of all three. The first just increment the variable number by one. The second thread waits for 5 seconds and then prints out the number variable, and the third thread prints out the number variable followed by an exclamation mark.

Since thread2 is waiting for 5 seconds before the System.out.println(number) call, the output looks like this:

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?