I have reading concurrency lately on java tutorials in oracle website.Today i read about deadlock/synchronization i am able to understand few things.
Synchronization :
synchronized methods: No two threads can invoke two different synchronized method of same object.Meaning at a given point in time onlyone synchronized methods gets executed per objects even if there are multiple other synch methods .
is my understanding proper.
Deadlock:
In below code deadlock occrus but i am just not able to understand why? why are both threading waiting for each other to get out of bow method ?
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();
}
}