关于Runnable和Thread的困惑

时间:2018-02-15 12:20:42

标签: java multithreading

我知道这是一个非常小的东西,对于你们这里的所有程序员来说都很容易,但是我被困住了。我无法理解为什么这段代码片段正在打印出来" Dog"而不是" 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();

1 个答案:

答案 0 :(得分:3)

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.