Threads with lambdas and runnable in Java I'm learning Java and I've started writing some tasks. Could you give me feedback for it?


  Write a static method andThen that takes as parameters two Runnable instances
   and returns a Runnable that runs the first, then the second. In the main method,
   pass two lambda expressions into a call to andThen , and run the returned
   instance.


public class Exercise7 {

    public static class Thread1 implements Runnable {

        @Override
        public void run() {
            System.out.println("Echo from thread1");
        }
    }

    public static class Thread2 implements Runnable {

        @Override
        public void run() {
            System.out.println("Echo from thread2");
        }
    }

    public static Runnable andThen(Runnable thread1, Runnable thread2) {

        return () -&gt; {
            thread1.run();
            thread2.run();
        };

    }

    public static void main(String[] args) {

        Runnable thread1 = new Thread1();
        Runnable thread2 = new Thread2();

       andThen(thread1,thread2).run();
    }
}
Your code is fine, but neither the question nor your answer have anything to do with threads. In order to run two separate threads, you need to create a Thread object with your runnable, rather than just calling myRunnable.run(). The first runnable returns to the scope of your main() method before the second is executed, i.e. they are sequential and exist in a single thread.