1查乒、actor實例之消息的接收與發(fā)送(異步?jīng)]有返回值)
2弥喉、actor實例之消息的接收與發(fā)送(同步有返回值)
1、actor實例之消息的接收與發(fā)送(異步有返回值)
ActorDemo3.scala
package day05
import scala.actors.{Actor, Future}
/**
* 用Actor實現(xiàn)同步和異步的消息的發(fā)送和消息的接收
*/
class ActorDemo3 extends Actor{
override def act(): Unit = {
while (true) {
// 偏函數(shù)
receive {
case "start" => println("starting...")
case AsynMsg(id,msg) => {
println(s"id:$id,Asyncmsg:$msg")
Thread.sleep(2000)
sender ! ReplyMsg(5,"success")
}
case SyncMsg(id,msg) => {
println(s"id:$id,SyncMsg:$msg")
Thread.sleep(2000)
sender ! ReplyMsg(5,"success")
}
}
}
}
}
object ActorDemo3 {
def main(args: Array[String]): Unit = {
val actorDemo3: ActorDemo3 = new ActorDemo3
actorDemo3.start()
// 異步發(fā)送消息玛迄,沒有返回值
// actorDemo3 ! AsynMsg(1,"Hi-- Honey")
// println("沒有返回值的異步消息發(fā)送完成")
// // 同步發(fā)送消息由境,線程等待返回值
// val content: Any = actorDemo3 !? SyncMsg(2,"Hi- lulu")
// println("有返回值的同步消息發(fā)送完成")
// println(content)
// 異步發(fā)送消息,有返回值憔晒,返回類型是Future[Any]
val reply: Future[Any] = actorDemo3 !! AsynMsg(3,"Hi-ningning")
Thread.sleep(1000)
if (reply.isSet) {
val value = reply.apply()
println(value)
}else {
println("None")
}
}
}
case class AsynMsg(id: Int, msg: String)
case class SyncMsg(id: Int, msg:String)
case class ReplyMsg(id: Int, msg: String)