原創聲明:轉載請指明原文出處: http://www.cnblogs.com/schoolbag/diary/2018/03/13/8563019.html 題目:通過子線程讀取每個文件,並統計單詞數,將單詞數返回給主線程相加得出總單詞數 ...
原創聲明:轉載請指明原文出處: http://www.cnblogs.com/schoolbag/diary/2018/03/13/8563019.html
題目:通過子線程讀取每個文件,並統計單詞數,將單詞數返回給主線程相加得出總單詞數
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 } }