Created
August 29, 2013 05:31
-
-
Save lu911/6374552 to your computer and use it in GitHub Desktop.
Actor Example ping-pong
This file contains 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
import scala.actors.Actor | |
object Main { | |
def main(args: Array[String]): Unit = { | |
val pong = new Pong | |
val ping = new Ping(100000, pong) | |
ping.start | |
pong.start | |
} | |
} | |
case object Ping | |
case object Pong | |
case object Stop | |
class Ping(count: Int, pong: Actor) extends Actor { | |
def act() { | |
var pingsLeft = count - 1 | |
pong ! Ping | |
while(true) { | |
receive { | |
case Pong => { | |
if (pingsLeft % 1000 == 0) println("Ping : pong") | |
if (pingsLeft > 0) { | |
pong ! Ping | |
pingsLeft -= 1 | |
} else { | |
println("Ping : stop") | |
pong ! Stop | |
exit() | |
} | |
} | |
} | |
} | |
} | |
} | |
class Pong extends Actor { | |
def act() { | |
var pongCount = 0 | |
while(true){ | |
receive { | |
case Ping => { | |
if (pongCount % 1000 == 0) println("Pong : ping " + pongCount) | |
sender ! Pong | |
pongCount += 1 | |
} | |
case Stop => { | |
println("Pong : stop") | |
exit() | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment