문제

I'm new to Scala and I'm trying to understand multithreading with actors. I wrote this piece of code and I don't understand some behaviour.

package sum
import scala.actors.Actor._

object ActorTest extends App {

  val caller = self

  val firstActor = actor {
    Thread.sleep(3000)
    println("Messages in mailbox: " + mailboxSize)
    receive {
      case x => println("First actor received: " + x)
    }
    println("Messages in mailbox: " + mailboxSize)
  }

  for(i <- 1 to 7)
  {
    firstActor ! "Hello" + i
    println("Message sent")
  }
}

this is the output:

Message sent
Message sent
Message sent
Message sent
Message sent
Message sent
Message sent
Messages in mailbox: 0
First actor received: Hello1
Messages in mailbox: 6

I don't understand why the first time, the messages in mailbox is 0, and the second time the messages in mailbox is 6 because all the messages are sent while the thread was asleep. I think I'm misunderstanding something. Can someone give me an explanation of this behaviour?

Thanks

도움이 되었습니까?

해결책

Untested and mostly guessed. I have never used Scala actors

I think it's an implementation detail. To me it's unclear when the body of the function passed to the actor function is executed.

It seems that it regards the mailbox as empty as long as you have not defined a recieve function. The recieve function is executed asynchronously, so I would recommend you to check the mailbox from within that function.

val firstActor = actor {
  receive {
    case x => 
      println("First actor received: " + x)
      println("Messages in mailbox: " + mailboxSize)
  }

  Thread.sleep(3000)
  println("Messages in mailbox: " + mailboxSize)
}

for(i <- 1 to 7)
{
  firstActor ! "Hello" + i
  println("Message sent")
}

I guess that the above code would print something similar to this:

Message sent
Message sent
Message sent
Message sent
First actor received: Hello2
Messages in mailbox: 4
Message sent
Message sent
First actor received: Hello1
Messages in mailbox: 6
...
Messages in mailbox: 6

Note that the output may be quite different as I can not predict in what order and at what speed the actor system handles messages.

As other said in comments, when you work with actors, the recommended library is Akka

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top