关于akka actor 修改相同变量

fudali
  • 129

我预期我的代码结果会是500000,结果总是比500000多,是akka actor并不能保证并发修改数据的准确性还是我代码哪里有问题???

class Piao extends Actor{

  override def receive: Actor.Receive = {
    case "+" => Piao.i = Piao.i-1
  }
}

object Piao{
  var i = 1000000;
}


class HelloAkka extends Actor{
  val Actor = context.actorOf(Props[Piao], name = "piao")
  override def receive: Receive = {
    case "+" ⇒
      for(i <- 1 to 100000)
        Actor ! "+"

    case _   ⇒ println("received unknown message")
  }
}

class TestAkka extends Actor{
  val Actor = context.actorOf(Props[Piao], name = "piao")
  override def receive: Receive = {
    case "+" =>
      for(i <- 1 to 400000)
        Actor ! "+"

    case _   => println("ooo")
  }
}

object MyApp extends App{
  val system = ActorSystem("MySystem")
  val myActor = system.actorOf(Props[HelloAkka], name = "hellakka")
  val testActor = system.actorOf(Props[TestAkka], name = "TestAkka")
  val Actor = system.actorOf(Props[Piao], name = "piao")
  testActor ! "+"
  myActor ! "+"
  Thread.sleep(3000)
  println(Piao.i)
}

请大神解惑,谢谢

回复
阅读 2.7k
2 个回答

actor能保证并发数据准确性,但是

object Piao{
  var i = 1000000;
}

并不能
HelloAkkaTestAkka可能会同时修改Piao.i,应当保证Piao.i同时只会被一个Actor修改,这样才能达到你要的效果

宣传栏