首先,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