Unexpected output. Please explain

I’ve been trying to figure out the reasons behind the output of the following Java program:

public class Main {
  public static void main(String args[]) {
    Runnable r = new Runnable() {
      @Override
      public void run() {
        System.out.println("Implementation");
      }
    };
    MyThread gaurav = new MyThread(r);
    new Thread(r).start();
    gaurav.start();
  }
}

class MyThread extends Thread {

  Runnable runnable;
  public MyThread(Runnable r) {
    runnable = r;
  }

  @Override
  public void run() {
    super.run();
    System.out.println("Thread");
  }
}

Output for above is : ‘Implementation’ followed by ‘Thread’ in next line. Now the problem lies in this statement :

gaurav.start();

As I have passed the runnable r to MyThread, I thought that r would get executed, hence, the output would be ‘Implementation’ for this too. But clearly, I am missing something. Also a difference between the statements:

new Thread(r).start();
        gaurav.start();

for this scenario would be really useful. Thanks.

Answer

Consider the following:

public class Main {
  public static void main(String args[]) {
    Runnable r = new Runnable() {
      @Override
      public void run() {
        System.out.println("Implementation");
      }
    };
    MyThread gaurav = new MyThread(r);
    gaurav.start();
  }
}

class MyThread extends Thread {

  Runnable runnable;
  public MyThread(Runnable r) {
    // calling Thread(Runnable r) constructor.
    super(r);
    // runnable isn't used anywhere. You can omit the following line.
    runnable = r;
  }

  @Override
  public void run() {
    // First it will run whatever Runnable is given
    // into Thread's constructor.
    super.run();
    System.out.println("Thread");
  }
}

Output:

Implementation
Thread

I guess your confusion comes from your Runnable field in MyThread. You think that by having it there, you somehow override Thread‘s own runnable but you don’t. If you want to do that, you should call super(r) in your constructor.

Leave a Reply

Your email address will not be published. Required fields are marked *