Actor 用于并行计算 ,Actor之间可以进行消息发送。
case class 是理想的载体,Actor的优势在于不基于资源与锁的基础上,完成并发。
Actor的建立
import scala.actors._
class ActorOps {
}
object helloActor extends Actor{
def act(): Unit ={
for (i<-1 to 5){
println("the is a scala actor")
Thread.sleep(2000)
}
}
}
object ActorOps{
def main(args: Array[String]) {
helloActor.start()
}
}
不常用的Actor创建
import scala.actors.Actor._
val secondActor=actor{
for (i<-1 to 5){
println(“the is a second scala actor”)
Thread.sleep(2000)
}
Actor的消息机制
!单方面传输
!?必须等到另一个Actor完成
!!取得发过去消息的结果
import scala.actors._
class ActorOps {
}
object helloActor extends Actor{
def act(): Unit ={
while (true){
receive{
case x:Int => println("got an Int")
case _=>println("some other type")
}
}
}
}
object ActorOps{
def main(args: Array[String]) {
helloActor.start()
helloActor ! "hi,the is scala!"
helloActor ! 1
}
Actor共享线程
通过react来进行线程共享
import scala.actors._
object NameResolver extends Actor{
import java.net.{InetAddress,UnknownHostException}
def act() {
react {
case Net(name: String, actor: Actor) => actor ! getIP(name)//actor处可以改成sender表示发送的那个actor 用于回复发来的Actor
case "EXIT" => println("exiting")
case msg =>
println("Unhandled message:" + msg)
act()
}
}
def getIP(name:String): Option[InetAddress] ={
try{
Some(InetAddress.getByName(name))
}catch {
case _:UnknownHostException=>None
}
}
}object ActorOps {
def main(args: Array[String]) {
NameResolver.start
NameResolver ! ("www.baidu.com",self)//self代表当前actor,所以下面的self.receive能接收到信息
println(self.receiveWithin(1000){case x=>x})
}
}
多个Actor协同工作
下面程序NameResolve把处理好的数据发给helloActor 。
好的actor使用case class来完成传递消息,结束时使用匹配模式。
import scala.actors._
import scala.actors.Actor._
class ActorOps {
}
object NameResolver extends Actor{
import java.net.{InetAddress,UnknownHostException}
def act() {
react {
case (name: String, actor: Actor) => actor ! getIP(name)//接受一个元组并把消息传给actor
// case Net(name: String, actor: Actor) => actor ! getIP(name)//使用case class传递数据
case "EXIT" => println("exiting")
case msg =>
println("Unhandled message:" + msg)
act()
}
}
def getIP(name:String): Option[InetAddress] ={
try{
Some(InetAddress.getByName(name))
}catch {
case _:UnknownHostException=>None
}
}
}
object helloActor extends Actor{
def act(): Unit ={
while (true){
receive{
case msg=> print("receive massage:"+msg)
case x:Int => println("got an Int")
case _=>println("some other type")
}
}
}
}
case class Net(name: String, actor: Actor)//case class
object ActorOps {
def main(args: Array[String]) {
NameResolver.start
NameResolver ! ("www.baidu.com",helloActor)//发送要解析的网址,发给的actor
// NameResolver ! Net("www.baidu.com",helloActor)
helloActor.start()
}
}