Thread object built with runnable overrides the launch method

Given this code example:

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();

Why is the conclusion Dog, not Cat?

+5
source share
5 answers

The implementation runin Threadjust calls Runnableprovided in the constructor, if any. You override this code, so if the new thread just has its own method run, called independently, is Runnableignored. Of course, you should be able to look at the source code to verify that ... (I just did this, and until I post the source here, it does exactly what I described).

, , - . Thread , . , Thread . , , , ;)

EDIT: , . start() :

; Java .

run() :

Runnable, Runnable object run; .

, run() start(), run(), , Runnable, .

, :

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

"CatDog".

+7

Thread.run, runnable. "".

+3

, run() . t :

public void run() {
System.out.print("Dog");
}

o/p cat, r.start(),

 public void run() {
    System.out.print("Cat");
  }
0

java.lang.Thread:

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

targetis the field Runnablein Threadthat the constructor Thread(Runnable)uses to assign your variable r. When you override a method runin Thread, you change the behavior runto a call

System.out.print("Dog");

instead of calling

if (target != null) {
    target.run();
}
0
source

This is an anonymous class, and you override / override run. Do you use the transmitted Runnablein yours run? No no. So the question is, why did you expect to print Cat?

 new Thread(r) {
  public void run() {
    System.out.print("Dog");
  }
};
-1
source

All Articles