Created
May 22, 2012 06:44
-
-
Save write2munish/2767135 to your computer and use it in GitHub Desktop.
Java Threading Synchronization example
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
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