יום רביעי, 16 באפריל 2014

Play with Scala actors

The following code is a little demonstration for Scala actors:

package myScalaProject
import scala.actors.Actor
import scala.actors.Actor._
import java.lang.Float
class ActorTester extends Actor {
def act() {
       println("Actor Started.")
       println ("The actor thread id :" +  Thread.currentThread().getId())
              loop {
                     receive {
                     case i: Int => println("Int: " + i.toString)
                     case s: String => println("String: " + s)      
                     case f: Float => println("Float: " + f) 
                     case 5=> println("Five")  
                     case _ => println("Default.")
                     }
              }
                 println("Actor ended.") //doesn’t called
       }
}     
object PlayWithActors {
 println ("The main thread thread id :" +  Thread.currentThread().getId())
 val myActorTester = new ActorTester
 myActorTester.start
 
 //Sending data to the actor
 myActorTester ! "Hello actor"
 myActorTester ! 5
 myActorTester !  164.1
 myActorTester ! 15
}

And the Result :


The main thread thread id :1
Actor Started.
The actor thread id :12
String: Hello actor
Int: 5
Default.
Int: 15

אין תגובות:

הוסף רשומת תגובה