首页 > 代码库 > Scala学习笔记--Actor和并发

Scala学习笔记--Actor和并发

未完成。

SimpleActor.scala

//actor是一个类似线程的实体,它有一个用来接收消息的信箱。//实现actor的方法是继承Scala.actors.Actor并完成其act方法//通过调用actor的start方法来启动它class SillyActor extends Actor{  def act(){    for(i<- 1 to 5){      println("Actor"+i)      Thread.sleep(1000);    }  }}object MyActor extends Actor{  def act (){    Actor.receive{      case x:Int =>println("got an Int: "+x)      case _ =>println("not an int")    }  }}object SimpleActor{  def main(args:Array[String]):Unit = {   /*     val sactor1 = new SillyActor();    sactor1.start();        //另一种方法:使用Actor中名为actor工具的方法来创建actor    //actor在定义后立即启动,无需在调用start()    val sactor2 = Actor.actor{      for(i<-1 to 5){        println("Another Actor"+i)        Thread.sleep(1000);      }    }   */        //另一种Actor,通过调用Actor.receive来接收消息    //	actor发送消息时,它并不会阻塞,当actor接收消息时,它也不会被打断。发送的消息在接收actor的邮箱中等待处理,知道actor调用receive方法    val sactor3 = Actor.actor{      Actor.receive{        case x :Int =>println("got an Int: "+x)        case _ =>println("not an Int");      }    }        sactor3 ! 12    //通过调用Actor.receive接收消息的另一种形式    MyActor.start()    MyActor ! 14        //将原生线程当成Actor    Actor.self ! 15;  //这句要放在前面,放在后面则程序不会停止    Actor.self.receive{      case x :Int =>println("got an Int: "+x)      case _ =>println("not an Int");    }    //Actor.self ! 15    /*     * 解释     * 如果使用原生线程,最好用receive的变种receiveWithin。     * 此方法可以指定一个以毫秒计的超时时限。     * 如果在解释器命令行中使用receive的话,receive将会阻塞命令行,直到有消息到来,     * 对self.receive而言,可能意味着永远等待下去。     * 应该使用receiveWithin。并给出超时值     * self.receiveWithIn(1000){case x => x}     * */      }}

  

ReactActor.java

object ReactActor{  def main(args:Array[String]):Unit={    NameResolver.start();    NameResolver ! ("www.baidu.com",Actor.self)        NameResolver ! "msg1";    NameResolver ! "EXIT"    NameResolver ! "msg2";//已经结束,不会显示  }}object NameResolver extends Actor{  def act(){    react{      case (name:String, actor:Actor)=>        println(getIp(name))        //actor ! getIp(name);        act();      case "EXIT" =>        println("Name resorver exit!");      case msg =>        println("Unhandled message" + msg);        act();    }  }    //获取IP地址  def getIp(name:String):Option[InetAddress]={    try{      Some(InetAddress.getByName(name))    }catch{      case _:UnknownHostException =>None    }  }}

  

 

Scala学习笔记--Actor和并发