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
.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With