Scala并发编程

在java中,基于共享数据、加锁的线程模型,使得java并发编程越来越复杂,而在Scala中采用actor模型,不共享数据,依赖消息传递的并发编程模型

object Actor_Message extends Actor {
  def act() {
    while(true){
        receive { //收件箱
          case msg => println("Message content Actor from inbox: " + msg)
        }
      }
  }
}
object Actor_Messages {

  def main(args: Array[String]) {
    val actor_Message = actor{ //创建匿名actor,默认启动
      while(true){
        receive { //作为偏函数,有apply方法和isDefinedAt方法,apply进行模式匹配。isDefinedAt判断消息能否被case处理,若是则返回true。
        //正常情况下,偏函数会先调用isDefinedAt验证(true还是false),确认apply调用时安全的,否则apply模式匹配时会异常
        //而actor做了透明处理,即使没有匹配的case,不会异常,只会忽略。receive会先调用isDefinedAt,如果返回true,才将消息传递给偏函数的apply方法;
        //最后apply方法处理消息。如果没有匹配成功,actor则会处于阻塞状态。
          case msg => println("Message content from inbox: " + msg)
        }
      }
    }
    val double_Message = actor{
        while(true){
            receive {
            case msg : Double => println("Double Number from inbox: " + msg)
//         case _ => println("Something Unkown" )
            }
        }
    }
    Actor_Message.start
    Actor_Message ! "Hadoop" //actor发送消息
    actor_Message ! "Spark"
    double_Message ! Math.PI
    double_Message ! "Hadoop"
    
  }

}

原生线程、case class消息传递下的偏函数解析

case class Person(name: String, age: Int)

class HelloActor extends Actor{
  def act(){
    while(true){
        receive { //把收到的消息传给偏函数
          case Person(name, age) => { //线性执行,不存在资源争用的情况
            println("Name: " + name + " : " + "Age: " + age)
            sender ! "Echo!!!" //给发送消息的actor回复消息。将计算结果以消息的方式传递给其他数据消费者,不要有全局共享的数据
                      }
          case _ => println("Something else...") //其他消息的处理,避免邮箱被占满
        }
      }
  }
}
object Actor_With_CaseClass {

  def main(args: Array[String]) {
    val hiActor = new HelloActor
    hiActor.start
    hiActor ! Person("Spark", 6) //发送者为main所在的actor
    
    self.receive{case msg => println(msg)} //self为当前main方法所在actor的引用,这里接收其他线程发送给主线程的消息
// self.receiveWithin(1000){case msg => println(msg)}
  }
}

react、loop,基于线程重用,让性能有所提升

object NameResolver extends Actor{
 
  def act(){
    react { //react处理完消息后没有返回
      case Net (name, actor) => 
        actor ! getIp(name) //这里actor就是main传过来的,即sender
        act //actor线程重复执行,如果不加act方法,线程运行完任务后将终止
      case "EXIT" => println("Name resolver exiting.")
      case msg => 
        println("Unhandled message : " + msg) 
          act
    }

    //这两种方式结果一样,写法不同而已
    loop {
      react {
     case Net (name, actor) => 
         actor ! getIp(name)
         
     case msg => 
         println("Unhandled message : " + msg) 
    }
    }
 
  }
  def getIp(name : String) : Option[InetAddress] = {
    try{
      println(InetAddress.getByName(name))
      Some(InetAddress.getByName(name))
    } catch {
      case _ : UnknownHostException => None
    }
  }
}

case class Net(name : String, actor: Actor)

object Actor_More_Effective {
  def main(args: Array[String]) {
    NameResolver.start
    NameResolver ! Net("www.baidu.com", self) //main所在actor发消息
    
    println(self.receiveWithin(1000){case x => x}) //main所在actor收消息
  }
}

你可能感兴趣的:(Scala并发编程)