Skip to content

Instantly share code, notes, and snippets.

@write2munish
Created May 22, 2012 06:44
Show Gist options
  • Save write2munish/2767135 to your computer and use it in GitHub Desktop.
Save write2munish/2767135 to your computer and use it in GitHub Desktop.
Java Threading Synchronization example
public class PingPong {
Agent<String> whoseTurn;
public PingPong(Agent<String> player) {
whoseTurn = player;
}
public boolean hit(final String opponent) {
final String x = Thread.currentThread().getName();
//wait till all the messages are processed to make
//you get the correct value, as updated to Agents are
//async
String result = whoseTurn.await(new Timeout(5, SECONDS));
if (x.compareTo(result) == 0) {
System.out.println("PING! (" + x + ")");
whoseTurn.send(opponent);
} else {
try {
wait(2500);
} catch (Exception e) {
}
}
return true; // keep playing.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment