我是scala的新手,我正在尝试用scala编写一个程序,它创建了多个(例如30个)actor,并在它们之间传递消息.
以下是我到目前为止所管理的内容:
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"
}
}
}
Run Code Online (Sandbox Code Playgroud)
该程序的目标是创建多个actor并将一个字符串从一个actor转发到另一个actor.
上面的代码创建了作为命令行参数给出的'N'个actor.这些actor由Main对象创建并启动.Main应该只向上面创建的一个actor发送消息.从Main接收消息的actor应该将相同的消息转发给另一个ALREADY创建/启动的actor.
这可能吗?如果是这样,你能指导我正确的方向吗?
在此先感谢,MS
首先,我建议查看Akka演员,很快将取代Scala 2.10中的Scala演员,希望在接下来的几个月里出演.
话虽如此,它绝对有可能,工作流程会像这样(至少在Akka):
ActorSystem在您的main方法中创建一个.Actor作为内的期望ActorSystem经由actorOf方法,该方法将返回一个ActorRef对象.ActorRef来发送消息.在Actor实现中,以某种方式使其Actor他人(可能通过构造函数)知道,并弄清楚你希望如何在String整个系统中传播(在本文中,我通常更喜欢使用Scala案例类作为消息).
这种声音就像一个像系统一样的状态机 - 我一直在玩的一个想法就是将它ActorSystem视为一个图形实体,这意味着Actor你为每个实例传递一个它的邻居列表(也许是a Vector[ActorRef]).
您还可以检查出新的Actor小号DSL的阿卡队近期推出.
要了解有关Akka的更多信息,我建议使用以下资源: