【发布时间】:2014-12-19 09:30:07
【问题描述】:
我现在正在做一个 scala 项目,我决定在 actor 模型上使用 Akka 的代理库,因为它允许更实用的并发方法。但是,我在运行许多不同的方法时遇到了问题代理一次。似乎我只能同时运行三到四个代理。
import akka.actor._
import akka.agent._
import scala.concurrent.ExecutionContext.Implicits.global
object AgentTester extends App {
// Create the system for the actors that power the agents
implicit val system = ActorSystem("ActorSystem")
// Create an agent for each int between 1 and 10
val agents = Vector.tabulate[Agent[Int]](10)(x=>Agent[Int](1+x))
// Define a function for each agent to execute
def printRecur(a: Agent[Int])(x: Int): Int = {
// Print out the stored number and sleep.
println(x)
Thread.sleep(250)
// Recur the agent
a sendOff printRecur(a) _
// Keep the agent's value the same
x
}
// Start each agent
for(a <- agents) {
Thread.sleep(10)
a sendOff printRecur(a) _
}
}
上面的代码创建了一个代理,它保存 1 到 10 之间的每个整数。底部的循环将 printRecur 函数发送给每个代理。程序的输出应该显示数字 1 到 10 每四分之一秒打印一次(尽管没有任何顺序)。但是,出于某种原因,我的输出只显示了输出的数字 1 到 4。
在 Akka 中是否有更规范的方式来使用代理?我来自 clojure 背景,并且之前在那里成功使用过这种模式,所以我天真地在 Scala 中使用了相同的模式。
【问题讨论】: