返回顶部

收藏

pingpong.scala

更多

使用 Actor 进行消息传递

pingpong.scala

package examples.actors

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)
      }
    }
  }
}

标签:Actors,Scala

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. 博主 发表 2011-08-16 07:00:00 使用maven进行scala项目的构建
  2. 方 腾飞 发表 2013-08-09 13:05:38 讨喜的隔离可变性(九)混合使用角色和STM
  3. 博主 发表 2013-08-02 14:07:00 Spray的模块结构
  4. 博主 发表 2013-05-05 14:02:00 Scala中的语言特性是如何实现的(1)
  5. Freewind 发表 2014-05-28 13:41:47 使用brew安装scala 2.8.x
  6. 博主 发表 2014-06-21 03:32:00 Desugar Scala(16) -- lower bound
  7. Freewind 发表 2011-09-12 17:56:38 scala,离天堂只差一步
  8. Freewind 发表 2011-09-13 14:34:35 关于flatMap的用法
  9. Freewind 发表 2013-01-01 09:00:59 06. Action 的组合
  10. hongjiang 发表 2014-10-05 12:20:43 scala雾中风景(16): println(1,2,3)为什么work?
  11. debugo 发表 2014-10-28 09:18:33 Spark as a Service之JobServer项目和命名RDD
  12. 博主 发表 2014-09-06 12:28:00 solving regular problems in scala