• Scala学习笔记之Actor多线程与线程通信的简单例子


     

    题目:通过子线程读取每个文件,并统计单词数,将单词数返回给主线程相加得出总单词数

     

    package review
    import scala.actors.{Actor, Future}
    import scala.collection.mutable.HashSet
    import scala.io.Source
    /**
      * @author Mr.Xu
      * @version v1.0
      *          Date:2018-03-12
      */
    //通过子线程读取每个文件,并统计单词数,将单词数返回给主线程相加得出总单词数
    
    //建立子线程Actor模型
    class Actor1 extends Actor{
      override def act(): Unit ={
       //使用轮询监听
        while (true){
          receive{
            case readFile(fname: String) =>{
              //匿名函数
              var num: Int = 0
              val read = Source.fromFile(fname)
              val lines = read.getLines()
              for (line <- lines) {
                num = num + line.toString.split(" ").length
              }
              }
              //返回给主线程的消息
              sender ! num
          }
        }
      }
    }
    //样例
    case class readFile(fname: String)
    case class result(fname: String,int: Int){
      println(fname+"文件的单词个数为"+int)
    }
    
    object ActorMain extends App {
      //文件集合
      var files = Array("E:\File\word\a.txt","E:\File\word\b.txt","E:\File\word\c.txt","E:\File\word\a.txt","E:\File\word\a.txt","E:\File\word\a.txt")
      val a = new Actor1
      a.start()  
      //返回结果集,可以用来判断该线程是否返回了结果
      var replySet = new HashSet[Future[Any]]
      var sum = 0
      for (f <- files){
        val reply:Future[Any] = a !! readFile(f)
        replySet +=reply
      }
      //若该线程执行完成并返回了结果,则将各个结果累加,并将该线程从结果集合中移除
      while (replySet.nonEmpty){
        val toC =replySet.filter(_.isSet)
        for (r <- toC){
          val reply:Any = r.apply()
          sum=sum+count(reply)
          replySet.remove(r)
        }
      }
      println("总的单词数为:"+sum)
      //取整型函数
      def count(s:Any): Int ={
      s.toString.toInt
      }
    }

    小徐看世界,世界如此多娇: http://www.cnblogs.com/schoolbag/diary/2018/03/13/8563019.html

  • 相关阅读:
    应用Solaris11放置光盘修复solaris引导妨碍
    HP 3803TX 装置debian4 Linux
    释放linux细碎的内存
    linux批量查找文件内容
    Oracle 10g R2 for Solaris x86在Solaris 11上的装配
    Linux 零碎进修之shell剧本进修
    华硕易PC台式机版7月环球上市 或运转Linux
    Linux文件琐细 一分钱一分货
    linux下平安管理
    预装Windows或Ubuntu,戴尔出Mini Inspiron 8.9寸笔记本
  • 原文地址:https://www.cnblogs.com/schoolbag/p/8563296.html
Copyright © 2020-2023  润新知