题目:通过子线程读取每个文件,并统计单词数,将单词数返回给主线程相加得出总单词数
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