Skip to content

Instantly share code, notes, and snippets.

@tarrsalah
Created August 25, 2013 10:29
Show Gist options
  • Select an option

  • Save tarrsalah/6333154 to your computer and use it in GitHub Desktop.

Select an option

Save tarrsalah/6333154 to your computer and use it in GitHub Desktop.
a Dead lock example
public class Dead {
private int state;
public Dead(int state) {
this.state = state;
}
public synchronized int getMyState() {
return state;
}
public synchronized int getYourState(Dead dle) {
return dle.getMyState();
}
@SuppressWarnings("SleepWhileHoldingLock")
public synchronized int getMineAndYours(Dead dle) {
int yours = 0, mine = 0;
try {
yours = getYourState(dle);
sleep(2000);
mine = dle.getYourState(this);
} catch (InterruptedException ex) {
Logger.getLogger(Dead.class.getName()).log(Level.SEVERE, null, ex);
}
return (yours + mine);
}
public static void main(String[] args) {
final Dead us, them;
us = new Dead(1);
them = new Dead(10);
new Thread(new Runnable() {
public void run() {
System.out.println(us.getMineAndYours(them));
}
}).start();
new Thread(new Runnable() {
public void run() {
System.out.println(them.getMineAndYours(us));
}
}).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment