package test.scala.lang.actor import scala.actors.Actor object TestScalaActor { def main(args: Array[String]): Unit = { testActor testActor2 } // 通过扩展类创建actor def testActor = { //要启动一个actor, 需要先构造一个实例, 并调用start方法 val actor = new HiActor actor.start() // 向actor发送消息 actor ! "Hi" actor ! "Hii" } // 创建临时actor // 通过 Actor伴生对象 actor 方法创建和启动actor def testActor2 = { val actor2 = Actor.actor { while (true) { Actor.receive { case "Hi" => println("2Hello") case _ => println("2please say Hi") } } } actor2 ! "Hi" actor2 ! "Hii" val actor3 = Actor.actor{ while(true) { Actor.receive{ case MsgA => println("MsgA") case MsgB => println("MsgB") case _ => println("some message") } } } actor3 ! MsgA actor3 ! MsgB actor3 ! "Hi" } } case class MsgA() case class MsgB() // actor 扩展scala.actors.Actor, // 有一个抽象方法 act, 重写该方法制定该actor的行为 class HiActor extends Actor { // act 方法 和 Java Runnable的run 方法类似 def act() { while (true) { receive { case "Hi" => println("Hello") case _ => println("please say Hi") } } } }