scala学习笔记(十七) Actor

Actor模型框架是我最早学习scala的主要目标,通过actor消息驱动式编程可以更加方便的实行各种多线程与异步处理。

 

package demo

 

importjava.awt.image.BufferedImage

importscala.collection.mutable.ArrayBuffer

importscala.util.Random

importcom.typesafe.config.ConfigFactory

importakka.actor.Actor

importakka.actor.ActorRef

importakka.actor.ActorSystem

importakka.actor.Props

importjavax.imageio.ImageIO

import java.io.File

importscala.io.Source

 

/**

 * @author Administrator

 */

object ScalaActor {

  val system =ActorSystem("MasterApp",ConfigFactory.load.getConfig("multiThread"))

  val wordFindResult =system.actorOf(Props[WordFindResultActor], "wordFindResult")

  def main(args: Array[String]): Unit = {

 

    //   system.actorOf(Props(new Actor() {

    //     val excAvg = context.system.actorOf(Props[ExcAvg], "excAvg")

    //     val ls = Random.shuffle((0l to 10000000l).toList)

    //     val t1 = System.currentTimeMillis()

    //     excAvg ! Data(ls)

    //     def receive = {

    //       case Result(avg: Long) =>

    //         println("\nAvg value is :" + (avg / ls.length))

    //         val t2 = System.currentTimeMillis()

    //         println(t2 - t1)

    //         println("\nSingle thread Avg value is :" + (ls.sum /ls.length))

    //         println(System.currentTimeMillis() - t2)

    //         system.shutdown()

    //     }

    //   }))

 

    val file = newFile("""E:\workspace\ddt7.0\src\game\gameServer\data\prop""")

 

    readFiles(file)

    //   

    //  if( "class".matches("clas*")){

    //    println("----")

    //  }

  }

 

  def readFiles(file: File) {

    if (file.isDirectory()) {

      file.listFiles().map { readFiles }

    } else {

      val wordFind =system.actorOf(Props[WordFindActor])

 

      wordFind ! WordFindData("prop",file, wordFindResult)

    }

 

  }

 

  class ExcAvg extends Actor {

    var sd: ActorRef = null

    val array = ArrayBuffer[Long]()

    def receive = {

      case Data(list: List[Long]) =>

        sd = context.sender()

        if (list.length > 10000) {

          val (l1, l2) =list.splitAt(list.length / 2)

          val excAvg1 =context.system.actorOf(Props[ExcAvg])

          excAvg1 ! Data(l1)

          val excAvg2 =context.system.actorOf(Props[ExcAvg])

          excAvg2 ! Data(l2)

        } else {

          val r = list.sum

          sender ! Result(r)

        }

      case Result(avg: Long) =>

        //        println("result : "+avg)

        array += avg

        if (array.length == 2) {

          val r = array.sum

          sd ! Result(r)

        }

    }

  }

 

  sealed trait Message

  case class Result(avg: Long) extends Message

  case class Data(list: List[Long]) extendsMessage

 

  class ImageReaderActor extends Actor {

    def receive = {

      case fileName: String =>

        val bi = ImageIO.read(newFile(fileName));

    }

  }

 

  class WordFindActor extends Actor {

    def receive = {

      case WordFindData(key, file, replyTo)=>

        val words = Source.fromFile(file,"UTF-8").mkString.split("\\s+")

        val tmp = ArrayBuffer[String]()

        words.foreach { x =>

          if (x.trim().matches(key) &&!tmp.contains(x)){

            tmp += x

          }

        }

        replyTo ! WordFindResult(file.getName,tmp)

    }

  }

 

  class WordFindResultActor() extends Actor {

    var sum = 51

    var map = Map[String,ArrayBuffer[String]]()

    var wordCount = 0

    def receive = {

      case WordFindResult(fileName, array)=>

        sum -= 1

        wordCount += array.length

        for(key <- array) {

          val ab = map.getOrElse(key,ArrayBuffer[String]())

          if (ab.isEmpty) {

            map += (key -> ab)

          }

          if (!ab.contains(fileName)) {

            ab += fileName

          }

        }

 

        if (sum <= 0) {

          println("matchcount" + wordCount)

 

          map.foreach {

            e => println(e._1 + " ->" + e._2.mkString("[", ",", "]"))

          }

        }

    }

  }

 

  sealed trait WordFind

  case class WordFindResult(fileName: String,words: ArrayBuffer[String]) extends WordFind

  case class WordFindData(key: String, file:File, replyTo: ActorRef) extends WordFind

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ALAN-YOUNG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值