package com.dtspark.scala.basics
import scala.actors.Actor
/**
* Scala多线程实战
* 1:开发环境:Scala IDE(版本为:2.11.8)集成开发环境
* 2:引用jar包:scala-actors.jar,scala-actors-migration.jar
* 3:该实例使用Scala模式匹配以及Scala多线程使用技术
* Scala多线程并发调用方法为:
* 伴生类: class XXX extends Actor
* def act(){
* while(true){
* receive{
* case
* case
* }
* }
* }
* 伴生方法:object(){
* 实例化 XXX
* 调用start()方法
* }
*/
object HelloActor {
def main(args: Array[String]): Unit = {
val helloActor = new HelloActor
//调用scala多线程方法
helloActor.start()
val helloBackActor = new HelloBackActor(helloActor)
helloBackActor.start()
// var counter = 0
/*while (true) {
helloActor ! "Wow" + counter
counter += 1
Thread.sleep(3000)
}*/
// helloActor ! Hello("Spark", "Spark means Dollars")
}
}
case class Hello(name: String, content: String, sender:Actor)
case class HelloBack(name: String, content: String, sender:Actor)
class HelloActor extends Actor{
var counter = 0
def act() {
while(true){
receive {
case content:String => println("Message: " + content)
case Hello(name, content,sender) => {
println("HelloActor : " + "name: " + name + " content: " + content + counter)
counter += 1
Thread.sleep(3000)
sender ! HelloBack(name, content+counter, this)
}
}
}
}
}
class HelloBackActor(val helloActor: Actor) extends Actor{
var counter = 0
def act() {
helloActor ! Hello("Spark", "Love is here", this)
while(true){
receive {
case content:String => println("Message: " + content)
case HelloBack(name, content,sender) => {
println("HelloBackActor : " + "name: " + name + " content: " + content + counter)
counter += 1
Thread.sleep(3000)
sender ! Hello(name, content+counter, this)
}
}
}
}
}
//运行结果为:
HelloActor : name: Spark content: Love is here0
HelloBackActor : name: Spark content: Love is here10
HelloActor : name: Spark content: Love is here111
HelloBackActor : name: Spark content: Love is here1121
HelloActor : name: Spark content: Love is here11222
HelloBackActor : name: Spark content: Love is here112232
HelloActor : name: Spark content: Love is here1122333
HelloBackActor : name: Spark content: Love is here11223343
本文出自 “8381513” 博客,谢绝转载!
原文地址:http://8391513.blog.51cto.com/8381513/1835455