Skip to content

Instantly share code, notes, and snippets.

@hedgerh
Last active August 29, 2015 13:56
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 hedgerh/8985954 to your computer and use it in GitHub Desktop.
Save hedgerh/8985954 to your computer and use it in GitHub Desktop.
This version works, but it's because I added a wait(200) after the first wait. The problem without the wait(200) is that sometimes the girl monitor wakes up and "asks Boy to confirm" before the boy can even ping.

This version works, but it's because I added a wait(200) after the first wait. The problem without the wait(200) is that sometimes the girl monitor wakes up and "asks Boy to confirm" before the boy can even ping.

import java.applet.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
// Attempt at a simple handshake. Girl pings Boy, gets confirmation.
// Then Boy pings girl, get confirmation.
class Monitor {
String name;
public Monitor (String name) { this.name = name; }
public String getName() { return this.name; }
// Girl thread invokes ping, asks Boy to confirm. But Boy invokes ping,
// and asks Girl to confirm. Neither Boy nor Girl can give time to their
// confirm call because they are stuck in ping. Hence the handshake
// cannot be completed.
public synchronized void ping (Monitor p) {
p.release();
System.out.println(this.name + " (ping): pinging " + p.getName());
try { wait(); wait(200); } catch (Exception e) { }
System.out.println(this.name + " (ping): asking " + p.getName() + " to confirm");
p.confirm(this);
System.out.println(this.name + " (ping): got confirmation");
p.release();
}
public synchronized void confirm (Monitor p) {
System.out.println(this.name+" (confirm): confirm to "+p.getName());
}
public synchronized void release () {
notify();
}
}
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 a = new Monitor("Girl");
Monitor b = new Monitor("Boy");
(new Runner(a, b)).start();
(new Runner(b, a)).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment