<分区>
我最近在 oracle 网站上阅读了有关 java 教程的并发性。今天我阅读了有关死锁/同步的内容,我能够理解一些事情。
同步:
同步方法:没有两个线程可以调用同一对象的两个不同的同步方法。这意味着在给定的时间点,即使有多个其他同步方法,每个对象也只会执行一个同步方法。
我的理解对吗?
死锁:
在下面的代码中出现了死锁,但我就是不明白为什么?为什么两个线程都在等待对方退出 bow 方法?
package com.tutorial;
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();
}
}