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
本文主要介绍了使用Scala的Actor模型框架进行消息驱动式编程,实现多线程与异步处理的方法。通过实例展示了如何利用Actor系统进行数据处理、文件读取、并发计算等操作。
416

被折叠的 条评论
为什么被折叠?



