7

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.

KunLun
  • 3,109
  • 3
  • 18
  • 65
  • What is your requirement? This question is vague. What type of a function do you need? – Ravindra Ranwala Sep 26 '19 at 14:09
  • @RavindraRanwala I want to do this `Function?, ??> runImpl = () -> { //runnable implementation }` and when I create a new Thread to do like this `new Thread(runImpl)` – KunLun Sep 26 '19 at 14:10
  • 9
    You don't need a function. How about this: `Runnable task = () -> System.out.println("My task");` – Ravindra Ranwala Sep 26 '19 at 14:12
  • @RavindraRanwala I didn't thinking at that, thank you. – KunLun Sep 26 '19 at 14:14
  • Unfortunately, taking this idea one step further, as I asked in [this question](https://stackoverflow.com/q/36336848/3182664), is not possible. But fortunately, for your specific case, using `Runnable` will do it. – Marco13 Sep 26 '19 at 18:03

1 Answers1

3

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();
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
  • 1
    …and the OP did already implement `Runnable` via lambda expression when using `new Thread(() -> { //do things }).start();`… – Holger Sep 27 '19 at 16:21