Scala并发编程【消息机制】
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 !"
结果: