flying3615
1/6/2017 - 8:32 AM

Akka calculate 10000 in 4 concurrent actors

Akka calculate 10000 in 4 concurrent actors

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()

}