Scala 範例程式 - Actor 的使用 (Pingpong)

原始程式:pingpong.scala

import scala.actors.Actor
import scala.actors.Actor._

abstract class PingMessage
case object Start extends PingMessage
case object SendPing extends PingMessage
case object Pong extends PingMessage

abstract class PongMessage
case object Ping extends PongMessage
case object Stop extends PongMessage

object pingpong extends Application {
  val pong = new Pong
  val ping = new Ping(100000, pong)
  ping.start
  pong.start
  ping ! Start
}

class Ping(count: Int, pong: Actor) extends Actor {
  def act() {
    println("Ping: Initializing with count "+count+": "+pong)
    var pingsLeft = count
    loop {
      react {
        case Start =>
          println("Ping: starting.")
          pong ! Ping
          pingsLeft = pingsLeft - 1
        case SendPing =>
          pong ! Ping
          pingsLeft = pingsLeft - 1
        case Pong =>
          if (pingsLeft % 1000 == 0)
            println("Ping: pong from: "+sender)
          if (pingsLeft > 0)
            self ! SendPing
          else {
            println("Ping: Stop.")
            pong ! Stop
            exit('stop)
          }
      }
    }
  }
}

class Pong extends Actor {
  def act() {
    var pongCount = 0
    loop {
      react {
        case Ping =>
          if (pongCount % 1000 == 0)
            println("Pong: ping "+pongCount+" from "+sender)
          sender ! Pong
          pongCount = pongCount + 1
        case Stop =>
          println("Pong: Stop.")
          exit('stop)
      }
    }
  }
}

執行結果:

D:\scala>scalac pingpong.scala

D:\scala>scala pingpong
Ping: Initializing with count 100000: Pong@187aeca
Ping: starting.
Pong: ping 0 from Ping@150bd4d
Ping: pong from: Pong@187aeca
Pong: ping 1000 from Ping@150bd4d
Ping: pong from: Pong@187aeca
Pong: ping 2000 from Ping@150bd4d
Ping: pong from: Pong@187aeca
Pong: ping 3000 from Ping@150bd4d
Ping: pong from: Pong@187aeca
Pong: ping 4000 from Ping@150bd4d
Ping: pong from: Pong@187aeca
....
....
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License