首先,here's a sample:在Java中如何同步工作
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();
}
}
什么我不明白是怎么的发生堵塞。主函数启动两个线程,每个线程开始自己的弓。
'synchronized'block究竟是什么?运行同一个对象的相同功能(正如我原先所想的那样)?同一个类的所有对象都具有相同的功能?同一个对象的所有同步函数?所有同一类的所有对象的同步函数?
帮我看看这里。
噢好吧。所以锁属于整个对象。我不知道为什么我认为它只是调用同一个被阻塞的给定对象的同步方法。 我想那回答我的问题。 – 2009-04-15 00:04:32