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() 的调用,但仍未被重写!
我是不是弄错了,因为这段代码可以工作
最佳答案
是的,你错了。首先,你很困惑overloading与 overriding .
第二,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/