前言
Akka 是一个用 Scala 编写的库,用于简化编写容错的、高可伸缩性的 Java 和 Scala 的 Actor 模型应用。
它已经成功运用在电信行业。
言归正传
1、添加maven依赖
代码语言:javascript复制 org.scala-lang
scala-library
2.11.12
com.typesafe.akka
akka-actor_2.11
2.4.17
com.typesafe.akka
akka-remote_2.11
2.4.17
2、实现代码
代码语言:javascript复制import akka.actor.{Actor, ActorRef, ActorSystem, Props}
class PersonOne extends Actor {
override def receive: Receive = {
case "start" => {
println("PersonOne:.........(前文)")
}
case "question1" => {
println("PersonOne: 你有病啊!")
Thread.sleep(2000)
sender() ! "question1"
}
case "question2" => {
println("PersonOne:有药你吃啊!")
Thread.sleep(2000)
sender() ! "question3"
}
case "question4" => {
println("PersonOne:吃多少有多少!")
Thread.sleep(2000)
sender() ! "question3"
}
}
}
class PersonTwo(val Person1:ActorRef) extends Actor {
override def receive: Receive = {
case "start" => {
Thread.sleep(2000)
println("PersonTwo:.........(前文)")
Thread.sleep(2000)
Person1 ! "question1"
}
case "question1" => {
println("PersonTwo: 你有药啊!")
Thread.sleep(2000)
Person1 ! "question2"
}
case "question3" => {
println("PersonTwo:有多少吃多少!")
Thread.sleep(2000)
Person1 ! "question4"
}
}
}
object CrossTalk extends App {
private val crossTalk = ActorSystem("weChatApp")
private val personOne:ActorRef = crossTalk.actorOf(Props[PersonOne](),"personOne")
private val personTwo:ActorRef = crossTalk.actorOf(Props[PersonTwo](new PersonTwo(personOne)),"personTwo")
println("模拟相声:《你要折腾》")
personOne ! "start"
personTwo ! "start"
}
3、运行结果