Last active
January 6, 2017 08:33
-
-
Save flying3615/bbc0f09c0ba4dc510dcb5d1e0d3b8a20 to your computer and use it in GitHub Desktop.
Akka calculate 10000 in 4 concurrent actors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package chapter4 | |
import akka.actor.{Actor, ActorSystem, Props} | |
import akka.routing.RoundRobinPool | |
/** | |
* Created by Administrator on 2017/1/6. | |
*/ | |
sealed trait SumTrait | |
case class Result(value: Int) extends SumTrait | |
class SumActor extends Actor { | |
val RANGE = 10000 | |
def calculate(start: Int, end: Int, flag: String): Int = { | |
var cal = 0 | |
for (i <- (start to end); _ <- 1 to 3000000) { | |
cal += i | |
} | |
println(s"flag:$flag") | |
cal | |
} | |
override def receive: Receive = { | |
case value: Int => sender ! Result(calculate((RANGE / 4) * (value - 1) + 1, (RANGE / 4) * value, value.toString)) | |
case _ => println("unknown error") | |
} | |
} | |
class PrintActor extends Actor{ | |
override def receive: Receive = { | |
case (sum:Int,startTime:Long) => println(s"All sum=$sum and time elapses ${(System.nanoTime()-startTime)/1000000000.0} seconds") | |
case _ => println("unknown print error") | |
} | |
} | |
class MasterActor extends Actor{ | |
var sum = 0 | |
var count = 0 | |
var startTime:Long = 0 | |
val sumActor = context | |
.actorOf( | |
Props[SumActor] | |
.withRouter(RoundRobinPool(nrOfInstances = 4)),name="sumActor") | |
val printActor = context.actorOf(Props[PrintActor],name="printActor") | |
override def receive: Receive = { | |
case "calculate..." => | |
startTime = System.nanoTime() | |
for(i <- 1 to 4) sumActor ! i | |
case Result(value) => | |
sum+=value | |
count+=1 | |
if(count==4){ | |
printActor ! (sum,startTime) | |
context.stop(self) | |
} | |
case "in for" => | |
val RANGE = 10000 | |
var cal = 0 | |
val startTime = System.nanoTime() | |
for(i <- 1 to RANGE; _ <- 1 to 3000000) { | |
cal +=i | |
} | |
val endTime = System.nanoTime() | |
println(s"All sum=$cal and time elapses ${(endTime-startTime)/1000000000.0} in for") | |
case _ => println("unknown error in Master actor") | |
} | |
} | |
object AkkTest extends App{ | |
var sum = 0 | |
val system = ActorSystem("MasterActorSystem") | |
val masterActor = system.actorOf(Props[MasterActor],name="masterActor") | |
masterActor ! "calculate..." | |
masterActor ! "in for" | |
Thread.sleep(1000) | |
system.terminate() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment