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 toandThen
, 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 () -> {
thread1.run();
thread2.run();
};
}
public static void main(String[] args) {
Runnable thread1 = new Thread1();
Runnable thread2 = new Thread2();
andThen(thread1,thread2).run();
}
}
2 Answers 2
Your solution does what has been asked, however for some simple improvements I'd look at removing the duplicate code as the Thread1
and Thread2
classes only diff in their name. So I'd delete one of the classes and pass a name parameter, now called NamedThread
...
public static class NamedThread implements Runnable {
private final String name;
NamedThread(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("Echo from " + name);
}
}
We can also improve the solution to make it reusable and extendable, for example, say we wanted it to work for 3 threads. So andThen
can accept any number of
Runnable
s and call run()
on each of then
public static Runnable andThen(Runnable... runnables) {
return () -> Arrays.asList(runnables).forEach(Runnable::run);
}
We can then improve main and remove the local variables
public static void main(String[] args) {
andThen(new NamedThread("thread1"),
new NamedThread("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.
thread1
andthread2
are "threads" in name only. There is no multithreading going on: all of your code is running on the main thread. \$\endgroup\$