多线程和匿名类和对象

时间:2013-10-02 12:34:37

标签: java multithreading runnable

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

*/

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

但是当我们传递这个新的Runnable对象时,它有 ITS OWN run()方法重载。所以* new Thread对象仍然没有重载run()方法。* 新线程(....)。start 的调用是对仍未被覆盖的线程的run()!! 我错了,导致此代码工作

3 个答案:

答案 0 :(得分:2)

是的,你错了。首先,您将overloadingoverriding混为一谈。

第二,the javadoc of Thread解释了如何创建线程:

  

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

     

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

答案 1 :(得分:1)

每当你想知道JDK中的某些东西是如何工作的时候,just have a look。在这种特殊情况下,这将是您在Thread类中找到的内容:

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

显然,定义并实现了该方法,并且实现说“调用传入的Runnable的run方法”。

答案 2 :(得分:0)

来自documentation

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()上调用的Thread方法是run()

Runnable
相关问题