Last active
January 4, 2016 07:39
-
-
Save rosshadden/8590173 to your computer and use it in GitHub Desktop.
cs4003 - 2
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
class Monitor { | |
String name; | |
public volatile boolean locked = false; | |
public Monitor(String name) { | |
this.name = name; | |
} | |
public String getName() { | |
return this.name; | |
} | |
public synchronized void ping(Monitor mon) { | |
try { | |
while (this.isLocked()) { | |
wait(); | |
} | |
} catch(InterruptedException e) { | |
Thread.currentThread().interrupt(); | |
} | |
System.out.println(this.name + " (ping): pinging " + mon.getName()); | |
mon.lock(); | |
System.out.println(this.name + " (ping): asking " + mon.getName() + " to confirm"); | |
mon.confirm(this); | |
System.out.println(this.name + " (ping): got confirmation"); | |
mon.unlock(); | |
notifyAll(); | |
} | |
public synchronized void confirm(Monitor mon) { | |
System.out.println(this.name + " (confirm): confirm to " + mon.getName()); | |
} | |
public synchronized void lock() { | |
System.out.println(this.name + " (lock)"); | |
this.locked = true; | |
} | |
public synchronized void unlock() { | |
System.out.println(this.name + " (unlock)"); | |
this.locked = false; | |
} | |
public boolean isLocked() { | |
System.out.println(this.name + " (isLocked): " + this.locked); | |
return this.locked; | |
} | |
} | |
class Runner extends Thread { | |
Monitor m1, m2; | |
public Runner(Monitor m1, Monitor m2) { | |
this.m1 = m1; | |
this.m2 = m2; | |
} | |
public void run() { | |
m1.ping(m2); | |
} | |
} | |
public class DeadLock { | |
public static void main(String args[]) { | |
int i = 1; | |
System.out.println("Starting..." + (i++)); | |
Monitor girl = new Monitor("Girl"); | |
Monitor boy = new Monitor("Boy"); | |
(new Runner(girl, boy)).start(); | |
(new Runner(boy, girl)).start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment