For example
import scala.actors.Actor
import scala.actors.Actor._
object Main {
class Pong extends Actor {
def act() {
var pongCount = 0
while (true) {
receive {
case "Ping" =>
if (pongCount % 1000 == 0)
Console.println("Pong: ping "+pongCount)
sender ! "Pong"
pongCount = pongCount + 1
case "Stop" =>
Console.println("Pong: stop")
exit()
}
}
}
}
class Ping(count: Int, pong: Actor) extends Actor {
def act() {
var pingsLeft = count - 1
pong ! "Ping"
while (true) {
receive {
case "Pong" =>
if (pingsLeft % 1000 == 0)
Console.println("Ping: pong")
if (pingsLeft > 0) {
pong ! "Ping"
pingsLeft -= 1
} else {
Console.println("Ping: stop")
pong ! "Stop"
exit()
}
}
}
}
}
def main(args: Array[String]): Unit = {
val pong = new Pong
val ping = new Ping(100000, pong)
ping.start
pong.start
println("???")
}
}
I try to print "???" after the two actors call exit(), but now it is printed before "Ping: Stop" and "Pong stop"
I have try have a flag in the actor, flag is false while actor is running, and flag is true when actor stops, and in the main func, there is a while loop, such as while (actor.flag == false) {}
, but it doesn't works, it is a endless loop:-/
So, please give me some advice.
If you need synchronous calls in akka, use ask pattern. Like
Also, you'd better use actor system to create actors.