1. 程式人生 > >Scala訊息機制Actor(舊版及新版Akka)

Scala訊息機制Actor(舊版及新版Akka)

1.入門

 1 package actor
 2 
 3 import scala.actors.Actor
 4 import scala.actors.migration.ActorDSL
 5 
 6 /**
 7   * Created by zhen on 2018/11/7.
 8   */
 9 class OldActor extends Actor{
10   def act(): Unit = {
11     println("scala2.10之前版本")
12     for(i <-1 to 2){
13       println("step:"+i)
14       Thread.sleep(1000)
15 } 16 } 17 } 18 object ActorDemo{ 19 def main(args: Array[String]) { 20 //老版本Actor 21 val oldActor = new OldActor() 22 oldActor.act() 23 val actor = ActorDSL.actor(new Actor { 24 override def act(): Unit = { 25 println("scala2.10之後版本使用Akka機制") 26 for(i <-1 to 2){
27 println("step:"+i) 28 Thread.sleep(1000) 29 } 30 } 31 }) 32 } 33 }

結果:

2.傳送訊息

 1 // 傳送訊息
 2     val actorMessage = ActorDSL.actor(new Actor {
 3       override def act(): Unit = {
 4         while(true){
 5           receive{
 6             case data : Int => println("age is : " + data)
7 case _ => println("something unknown !") 8 } 9 } 10 } 11 }) 12 actorMessage ! 18 13 actorMessage ! "hello everyone !"

結果: