zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    chapter02“良/恶性乳腺癌肿瘤预测”的问题
    ASCII编码和Unicode编码的区别
    Spring AOP概述
    Spring 基于注解的配置
    Spring Bean作用域&FactoryBean
    Spring <bean> 之间的关系&整合多个配置文件
    Spring 方法注入
    Spring 简化装配Bean的配置方式
    Spring 注入参数详解
    vue-router 导航守卫
  • 原文地址:https://www.cnblogs.com/schoolbag/p/8563296.html
Copyright © 2011-2022 走看看