Scala部分:Scala中actor函数的通信学习(大数据开发面试必问)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值