package com.bjsxt.scala
import scala.actors.Actor
class MyActor extends Actor{
def act():Unit={
while(true){
receive {
case s:String=>println("value="+s)
case _=>println("no match...")
}
}
}
}
object Lesson_Actor {
def main(args:Array[String]):Unit={
val actor1=new MyActor()
actor1.start.start()
actor1!"hello word~"
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package com.bjsxt.scala
import scala.actors.Actor
case class Msg(actor:Actor,message:String)
/**
* actor与myactor之间的通信
*/
class MyActor01 extends Actor{
def act(): Unit={
while(true){
receive {
case msg:Msg=>{
if(msg.message.equals("hello~")){
println("hello~")
msg.actor!("hi~")
}else if(msg.message.equals("could we have a date?")){
println("could we have a date?")
msg.actor!("no...")
}
}
case _=>println("no match...") //case后边有空格
}
}
}
}
class MyActor02(actor:Actor) extends Actor{
actor ! Msg(this,"hello~")//对话中,actor首先发送信号
def act():Unit={
while(true){
receive {
case s:String=>{
if(s.equals("hi~")){
println("hi~")
actor!Msg(this,"could we have a date?")
}else if(s.equals("no...")){
println("no...")
println("xxxxxxxxxxxxxxx")
}
}
case _=>println("no matching...")
}
}
}
}
object LessonActor02 {
def main(args:Array[String]):Unit={
val actor1=new MyActor01()
val actor2=new MyActor02(actor1)
actor1.start()
actor2.start()
}
}
Scala部分:Scala中actor函数的通信学习(大数据开发面试必问)
最新推荐文章于 2024-06-21 13:54:04 发布