Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function which hold implementation of Runnable

I have this code:

new Thread(() -> {

    //do things

}).start();

new Thread(() -> {

    //do same things

}).start();

I know I can declare a function which hold lambda:

Function<Integer, Integer> add = x -> x + 1;

I want to make this function to hold implementation of Runnable from new Thread.

But I don't know what to put between <> of Function.

like image 531
KunLun Avatar asked Sep 26 '19 14:09

KunLun


1 Answers

java.util.Function can't represent a Runnable task because the Function takes in an argument and returns something, and conversely Runnable.run method does not take any argument and returns nothing. Even if you feel that Runnable is somewhat similar in nature to a Function<Void, Void>, even this assumption is wrong due to the same reason.

Given that Runnable is a single abstract method interface (It has only run method), you can merely implement it with a lambda expression. Also notice that this lambda is just a more succinct syntactic sugar to orthodox anonymous inner classes. Here's how it looks.

Runnable task = () -> System.out.println("My task");

You can use this Runnable instance as an ordinary Runnable command in your program. Here's such an example usage.

Thread t = new Thread(task);
t.start();
like image 125
Ravindra Ranwala Avatar answered Sep 20 '22 15:09

Ravindra Ranwala