java - 多线程和匿名类和对象

标签 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 接口(interface)的子类?)的匿名对象来创建一个新线程

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

最佳答案

是的,你错了。首先,你很困惑overloadingoverriding .

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

There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread.[...]

The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started.

关于java - 多线程和匿名类和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19137001/

相关文章:

java -cp "lib/*"与 java -cp "lib/*.jar"

java - 有没有Mysql备份和恢复java api

Java - 如何利用动态 jar 加载?

c - C中的主线程在一定时间后终止

具有可序列化和可运行队列元素的 Java ThreadPoolExecutor(编译错误 : no suitable constructor found for. ..)

java - 如何将类中创建的所有对象存储在 Java 中该类返回的单个数组中?

Android - C++ for 循环与从 Java 线程调用的 OpenMP(减少)并行化导致段错误

c++ - 我是否有在C++中使用std::condition_variable将线程置于死锁的风险?

java - 如何将库附加到 JAR 文件?

java - Android Runnable 不会重复