Reputation: 103
I read the tutorial from Oracle official site and saw this example
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) throws Exception{
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();
}
}
I dun understand why this would happen deadlock? For my understanding, thread alphonse executes done then releases the lock, then thread gaston will continue to execute, no deadlock.
Upvotes: 0
Views: 75
Reputation: 11411
You should run it and see. It will never exit.
When you get a thread dump you'll see the two threads:
"Thread-0" #14 prio=5 os_prio=31 cpu=16.42ms elapsed=8.92s tid=0x00007fb3e6000000 nid=0x6603 waiting for monitor entry [0x0000700004ef3000]
java.lang.Thread.State: BLOCKED (on object monitor)
at Deadlock$Friend.bowBack(Deadlock.java:17)
- waiting to lock <0x000000061fff4b78> (a Deadlock$Friend)
at Deadlock$Friend.bow(Deadlock.java:14)
- locked <0x000000061fff4b38> (a Deadlock$Friend)
at Deadlock$1.run(Deadlock.java:29)
at java.lang.Thread.run(java.base@15-ea/Thread.java:832)
and
"Thread-1" #15 prio=5 os_prio=31 cpu=0.71ms elapsed=8.92s tid=0x00007fb3e587ee00 nid=0x8e03 waiting for monitor entry [0x0000700004ff6000]
java.lang.Thread.State: BLOCKED (on object monitor)
at Deadlock$Friend.bowBack(Deadlock.java:17)
- waiting to lock <0x000000061fff4b38> (a Deadlock$Friend)
at Deadlock$Friend.bow(Deadlock.java:14)
- locked <0x000000061fff4b78> (a Deadlock$Friend)
at Deadlock$2.run(Deadlock.java:35)
at java.lang.Thread.run(java.base@15-ea/Thread.java:832)
Look at the ids of the monitors each has locked, and is waiting for.
You can see that the first thread is waiting for the lock that the second thread holds and vice versa.
Upvotes: 1