我是scala的新手,我正在嘗試在scala中編寫一個程序,它創建了多個(比如說30個)actor,並在它們之間傳遞消息。在scala中創建多個參與者
下面是我已經成功至今:
import scala.actors.Actor
import scala.util.Random
class MyActor(val id:Int, val N:Int) extends Actor {
def act() {
println ("Starting actor: " + id)
/**
react{
case str : String =>
println("Received Msg: " + str)
val randNo : Int = Random.nextInt(N)
println("Actor " + id + " Picking a random actor: " + randNo)
// Here, I should forward the message received to the ALREADY created and started actors
// val objActor = new MyActor(randNo : Int, N : Int)
// objActor.start
// objActor ! str
}
*/
}
}
object Main {
def main(args:Array[String]) {
if(args.length == 0)
{
println("Usage scala Main <numNodes>")
sys.exit()
}
val N : Int = (args(0)).toInt
// Starting all actors
for (i: Int <- 0 to N-1) {
val a = new MyActor(i : Int, N : Int)
println ("About to start actor " + a.id)
a.start
// a!"Broadcast this msg to all actors"
}
}
}
該計劃的目標是創建多個角色,並從一個演員轉發到另一個字符串。
上面的代碼創建'N'個參數作爲命令行參數。 這些actor由對象Main創建並啓動。 主要應該只發送一條消息給以上創建的演員之一。 從Main接收消息的actor應該將相同的消息轉發給另一個ALREADY創建/啓動的actor。
這可能嗎?如果是這樣,你能指導我正確的方向嗎?
由於提前, MS