该示例说明了死锁是如何发生的。有一点不太明白,就是当第一个调用实例alphone的方法bow的thead即将执行gaston.bowbBack(this)时,如果如果,该线程是否会释放锁并获取实例gaston的锁,假设,它不属于第二个线程?或者它会同时持有两个锁直到该方法的所有代码被完全执行?还有一个问题,有没有办法检查线程是否持有锁?
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();
}
}
最佳答案
1)一个线程可以有多个锁,就像这样
...
synchronized (obj1) {
System.out.println(1);
synchronized (obj2) {
System.out.println(2);
}
}
...
2) 我们可以检查线程是否持有锁 Thread.holdsLock(Object obj)
关于java - 一个线程可以同时持有两个锁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27296727/