码迷,mamicode.com
首页 > 其他好文 > 详细

蘑菇云行动前传第17课:Scala并发编程实战

时间:2016-08-08 01:02:56      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:编程技术   spark技术   

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” 博客,谢绝转载!

蘑菇云行动前传第17课:Scala并发编程实战

标签:编程技术   spark技术   

原文地址:http://8391513.blog.51cto.com/8381513/1835455

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!