什么是正确的逻辑输出,我得到的示例线程代码
问题描述:
这是我的示例线程代码。什么是正确的逻辑输出,我得到的示例线程代码
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());
synchronized(bower) { //this is the change
bower.bowBack(bower);
}
}
public 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) throws InterruptedException {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
// Thread.sleep(20);
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
这会陷入僵局。 但是,如果我在它做一个小的改变。我不使用'bower'作为同步块的监视器,而是使用'this',它不会陷入死锁。
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());
synchronized(this) { //This is the change.
bower.bowBack(bower);
}
}
public 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) throws InterruptedException {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
// Thread.sleep(20);
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
请帮我弄清楚上面这段代码显示的行为背后的正确原因。
答
所不同的是
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
在这里,为ObjectIdentifier是一个对象,其锁与同步语句代表监视器相关联的参考。
synchronized(bower)使用监视器从凉亭,它是一个不同的对象。 你为凉亭制作了一个锁。因为两个线程都将对象锁定在另一个线程中,所以会发生死锁。
并且synchronized(this)使用自己的监视器。你为自己的物体锁定。线程将对象锁定在相同的线程中,并且没有人在意。
如果我错了,请纠正我!
答
你想要达到的目标是,在向某人屈服时,你不能屈服。
我想补充到bowBack
方法和bow...()
+0
你的方法会导致僵局。这与我的第一段代码类似,我在bow()中使用了synchronized(bower)。 – Sadique
由于删除
synchronize(this)
或synchronize(bower)
澄清我的困惑。 +1。 – Sadique