Site icon

Create runnable task using functional interface – java8 lambda stream (example)

1. Functional Interface java 8:

The interface having one abstract method is called the functional interface. E.g. Comparator, Runnable interface. The runnable interface will look like as follows

@FunctionalInterface
public interface Runnable {
 public abstract void run();
}

We have discussed about the Create threads using runnable interface. In current post, we will see how can we create Runnable task using Java 8 lambda.

2. Create thread using anonymous class:

//Tradition approach 1
Thread traditionalThread = new Thread(new Runnable() {			
	@Override
	public void run() {
		System.out.println("Runnable Traditional approach 1");		
	}
});

3. Create task in java using Runnable functional interface:

We will simply omit the anonymous class and we will have much cleaner code as

Runnable myTask = () -> System.out.println("Runnable using Java 8 lambda approach");

4. Program – create task using runnable functional interface

package org.learn;

class MyTask implements Runnable {
	public void run() {
		System.out.println("Runnable Traditional approach 2");
	}
}

public class RunnableUsingJava8 {

	public static void main(String[] args) throws InterruptedException {
		// Tradition approach 1
		Thread traditionalThread = new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("Runnable Traditional approach 1");
			}
		});
		traditionalThread.start();

		// Tradition approach 2
		Thread traditionalThread2 = new Thread(new MyTask());
		traditionalThread2.start();

		// Runnable using java 8 lambda
		Runnable myTask = () -> System.out.println("Runnable using Java 8 lambda approach");
		Thread thread = new Thread(myTask);
		thread.start();
	}
}

5. Output – Task using runnable functional interface (java 8)

Runnable Traditional approach 1
Runnable Traditional approach 2
Runnable using Java 8 lambda approach
Exit mobile version