package p20140710
import scala.actors.Actor
import scala.actors.Actor._
/**
* Created by Rongsheng.Liu on 14-7-10.
*/
object Main extends App {
val numActors = 10;
var lst = List.empty[Actor];
val start = System.currentTimeMillis
buildChain(numActors, null, lst) ! "Die"
//do not use react in the main thread
/*
Note that in the main method we cannot replacereceive by react. The
reason is that the main thread (the JVM thread executing the main method)
should not terminate before it receives an "Ack" response. If you would use react,
!!its message handler would be registered with the actor runtime, !!
and then the main thread would terminate. When the main thread terminates,
!!all other threads those marked as daemons, including the threads of the actor runtime,!!
are terminated, too. This means that the entire application would terminate(all actors will be terminated)!
To avoid this problem, use react only inside an actor.
*/
//one actor runtime is one thread
receive {
case "Ack" =>
val end = System.currentTimeMillis;
println("Took " + (end - start) + "ms")
}
//lst is just a observer container,to identify the actor's actorid in the actor pool, should be deleted
def buildChain(size: Int, next: Actor, lst: List[Actor]): Actor = {
val a = actor {
react {
case "Die" =>
val from = sender
if (next != null) {
next ! "Die"
println("next Die " + size)
react {
case "Ack" => {
// val l=lst;
// val sef = self
// val siz = size
// val fr=sender
//after send "Die" to next actor,immediately go to wait for "Ack" msg from any actors
//as soon as receive a "Ack" msg from any actor,send a same "Ack" to its sender actor
from ! "Ack"
println("to previous ack " + size)
}
}
} else {
// val sef = self
// val siz = size
//come to here ,size=10
from ! "Ack"
println("last ack to previous")
}
}
}
if (size > 0) buildChain(size - 1, a, a :: lst)
else a
}
}
note that :all "Ack" should be replace with 'Ack,I did that in order for readability
output:
next Die 0
next Die 1
next Die 2
next Die 3
next Die 4
next Die 5
next Die 6
next Die 7
next Die 8
next Die 9
last ack to previous
to previous ack 9
to previous ack 8
to previous ack 7
to previous ack 6
to previous ack 5
to previous ack 4
to previous ack 3
to previous ack 2
to previous ack 1
to previous ack 0
Took 195'ms