Created
August 25, 2013 10:29
-
-
Save tarrsalah/6333154 to your computer and use it in GitHub Desktop.
a Dead lock example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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