Skip to content

Instantly share code, notes, and snippets.

@write2munish
Created May 22, 2012 06:16
Show Gist options
  • Save write2munish/2767029 to your computer and use it in GitHub Desktop.
Save write2munish/2767029 to your computer and use it in GitHub Desktop.
Java Threading Synchronization example
public class PingPong {
// state variable identifying whose turn it is.
private String whoseTurn = null;
public synchronized boolean hit(String opponent) {
String x = Thread.currentThread().getName();
if (x.compareTo(whoseTurn) == 0) {
System.out.println("PING! (" + x + ")");
whoseTurn = opponent;
notifyAll();
} else {
try { wait(2500); }
catch (InterruptedException e) { }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment