Actor通信

首页 » Spark » Actor通信
import scala.actors.Actor
/*
 * Actor 通信模型
 * 相当于线程
 */

//样例类
case class Message(actor:Actor,msg:String)


class MyActor01 extends Actor {
  //接收消息
  def act(): Unit = {
    while(true){
      receive{
        case message:Message => {
          if(message.msg.equals("zhazhalong")){
            println("zhazhalong")
            message.actor ! "hi~"
          }else if(message.msg.equals("hello")){
            println("hello")
          }
        }
        case _=>{
          println("默认")
        }
    }
  }
}
}
class MyActor02(actor:Actor) extends Actor {
 //给MyActor01发消息
  actor ! Message(this,"zhazhalong")
  
  
 def act(): Unit = {
    while(true){
  			receive{
  			case s:String => {
  			  if(s.equals("hi~")){
  			    println("hi~")
  			    actor ! Message(this,"hello")
  			  }
  			}
  			case _=>{
  				println("默认")
  			}
  			}
 }
}
}
object match_test {
  def main(args: Array[String]): Unit = {

    val actor01 = new MyActor01()
    val actor02 = new MyActor02(actor01)
    actor01.start()
    actor02.start()
    
    
    
  }
}




/*
//样例类
case class Test(var name:String,age:Int){
  
}
object match_test {
  def main(args: Array[String]): Unit = {
    val h1= Test("zhazhalong",18)
    	//自动实现toString,equals,copy,(var) setter.getter等方法
    h1.age
    h1.name="long"
  }
}

*/


/*
//match
object match_test {
  def main(args: Array[String]): Unit = {
    val tuple = (1,"zhazhalong",'c')
    val iter=tuple.productIterator
    while(iter.hasNext){
      val one=iter.next()
      MatchTest(one)
    }
  }
  def MatchTest(o:Any)={
    o match{
      //自动break
      case 'c'=>{
        println('c')
      }
      case 1=>{
    	  println('1')
      }
      case _=>{
        println("默认")
      }
    }
  }
}
*/
分享到:
赞(0) 打赏

评论 5

评论前必须登录!

 

  1. #1

    不错

    渣渣辉6个月前 (03-27)
  2. #2

    给你点赞

    笔记本6个月前 (03-28)
  3. #3

    挺明白的

    靓仔6个月前 (03-28)
  4. #4

    我也是渣渣6个月前 (03-28)
  5. #5

    good厉害了

    小白6个月前 (03-29)

觉得文章有用就打赏一下弟弟吧

支付宝扫一扫打赏

微信扫一扫打赏

Vieu4.5主题
专业打造轻量级个人企业风格博客主题!专注于前端开发,全站响应式布局自适应模板。
正在播放:

作者想对您说:

累了就停下来听首歌吧

听完后会给您一个好心情

最后

等到您不容易

还希望您能多待一会儿

      00:00/00:00