Skip to content

Instantly share code, notes, and snippets.

@rosshadden
Last active January 4, 2016 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rosshadden/8590173 to your computer and use it in GitHub Desktop.
Save rosshadden/8590173 to your computer and use it in GitHub Desktop.
cs4003 - 2
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