NoOb121
NoOb121

Reputation: 29

Confusion regarding Runnable and Thread

I know this is a very tiny thing and would be quite easy for all you programmers out here, but I am stuck. I am not able to understand why this code snippet is printing out "Dog" instead of "Cat".

Runnable r = new Runnable() {
    public void run() {
        System.out.print("Cat");
    }
};

Thread t = new Thread(r) {
    public void run() {
        System.out.print("Dog");
    }
};

t.start();

Upvotes: 2

Views: 84

Answers (1)

ttzn
ttzn

Reputation: 2623

Calling start() on a Thread object causes the JVM to spawn a new system thread which then proceeds to call the run method. Its default implementation looks something like this :

private Runnable target; // This is what you passed to the constructor

@Override
public void run() {
  if (target != null) {
    target.run();
  }
}

Since you have overriden this very method in your anonymous Thread subclass declaration, this code never gets called, and the Runnable you injected is simply never used.

Also, whenever possible, leave the Thread class alone and put your code in Runnables instead.

Upvotes: 3

Related Questions