Package Com.dtspark.scala.basics
Import Scala.actors.Actor
/**
* Scala multi-threaded combat
* 1: Development environment: Scala IDE (version: 2.11.8) integrated development environment
* 2: Reference jar package: Scala-actors.jar,scala-actors-migration.jar
* 3: This instance uses Scala pattern matching and Scala multithreaded use technology
* Scala Multithreading concurrent Invocation method is:
* Companion Class: Class XXX extends Actor
* def Act () {
* while (true) {
* receive{
* case
* case
* }
* }
* }
* Companion Method: Object () {
* Instantiate XXX
* Call the Start () method
* }
*/
Object Helloactor {
def main (args:array[string]): Unit = {
Val helloactor = new Helloactor
Calling Scala multithreaded methods
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 Was 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)
}
}
}
}
}
The result of the operation is:
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
This article from "8381513" blog, declined reprint!
Mushroom Cloud Action prequel 17th: Scala concurrent programming combat