Actor通信

2020-03-11 269次浏览 已收录 5个评论
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("默认")
      }
    }
  }
}
*/

渣渣龙, 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Actor通信
喜欢 (0)

您必须 登录 才能发表评论!

(5)个小伙伴在吐槽
  1. 不错
    渣渣辉2020-03-27 13:11
  2. 给你点赞
    笔记本2020-03-28 16:52
  3. 挺明白的
    靓仔2020-03-28 17:17
  4. 我也是渣渣2020-03-28 17:43
  5. good厉害了
    小白2020-03-29 18:21