0
public class Deadlock {
    static class Friend {
        private final String name;
        public Friend(String name) {
            this.name = name;
        }
        public String getName() {
            return this.name;
        }
        public synchronized void bow(Friend bower) {
            System.out.format("%s: %s"
                + "  has bowed to me!%n", 
                this.name, bower.getName());
            bower.bowBack(this);
        }
        public synchronized void bowBack(Friend bower) {
            System.out.format("%s: %s"
                + " has bowed back to me!%n",
                this.name, bower.getName());
        }
    }

    public static void main(String[] args) {
        final Friend alphonse =
            new Friend("Alphonse");
        final Friend gaston =
            new Friend("Gaston");
        new Thread(new Runnable() {
            public void run() { alphonse.bow(gaston); }
        }).start();
        new Thread(new Runnable() {
            public void run() { gaston.bow(alphonse); }
        }).start();
    }
}




/*

new Thread(new Runnable() {
                public void run() { gaston.bow(alphonse); }
            }).start();

*/

在上面的代码中,我们new Thread通过创建一个匿名类(Runnable 接口的子类?)的匿名对象来创建一个

但是当我们传递这个新Runnable对象时,它有它自己的run()方法重载。所以 *new Thread 对象仍然没有重载它的 run() 方法。* new Thread(....).start的调用是到仍然没有被覆盖的线程的run()!!我弄错了吗,因为这段代码有效

4

3 回答 3

2

是的,你错了。首先,您将重载覆盖混淆。

其次,Thread 的 javadoc解释了如何创建线程:

有两种方法可以创建一个新的执行线程。一种是将类声明为 Thread 的子类。这个子类应该覆盖类 Thread.[...] 的 run 方法

创建线程的另一种方法是声明一个实现 Runnable 接口的类。然后该类实现 run 方法。然后可以分配一个类的实例,在创建线程时作为参数传递,然后启动。

于 2013-10-02T12:41:40.237 回答
1

每当您想知道 JDK 中的某些东西是如何工作的时,只需看看. 在这种特殊情况下,这将是您在Thread类中找到的内容:

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

很明显,方法是定义和实现的,实现说的是“调用传入的Runnable的run方法”。

于 2013-10-02T12:49:27.837 回答
0

文档

public Thread(Runnable target)

Parameters:
target - the object whose run method is invoked when this thread is started. If null, this classes run method does nothing.

在对象run()上调用的方法是start()Threadrun()Runnable

于 2013-10-02T12:42:01.523 回答