多线程和akka实现两个数组交替打印

多线程

import java.util.concurrent.{CopyOnWriteArrayList => JList}

/** * Created by ctao on 2015/12/2. */
object Worker extends App {
  val seq1 = Seq(1, 2, 3, 4, 5)
  val seq2 = Seq(11, 12, 13, 14, 15)
  val jList = new JList[Int]()
  seq1.zip(seq2).foreach{x =>
    jList.add(x._1)
    jList.add(x._2)
  }

  @volatile
  var flag = false

  val a = new Runnable{
    override  def run(): Unit = jList.synchronized{
      while(jList.size>0){
        println(s"${Thread.currentThread().getName}:${jList.remove(0)}")

        /** * wait */
        while(!flag){
          jList.wait()
        }

        /** * 设置为false,唤醒线程,自己等待 */
        flag = false
        jList.notify()

      }
    }
  }


  val b = new Runnable{
    override  def run(): Unit = jList.synchronized{
      while(jList.size>0){
        println(s"${Thread.currentThread().getName}:${jList.remove(0)}")
        while(flag){
          jList.wait()
        }

        /** * 进入等待 */
        flag = true
        jList.notify()

      }
    }
  }


  new Thread(a).start()
  new Thread(b).start()

}

这里面主要就是用线程安全的变量以及线程安全的集合,还有避免死锁问题

akka实现

package com.linewell.akkademo

import akka.actor.{Actor, ActorSystem, Props}

/** * Created by ctao on 15-12-2. */
object WorkSystem extends App{
  case class Print(length:Int)


  class WorkActor1 extends Actor{
    val seq = Seq(1,2,3,4,5)
    val work2 = context.actorSelection("/user/work2")
    override def receive: Receive = {
      case Print(x) => x match {
        case i if i <5 =>println(s"${self.path}: ${seq(i)}")
          work2 ! Print(i)
        case _ => context.system.terminate()
      }
    }
  }

  class WorkActor2 extends Actor{
    val seq = Seq(11,12,13,14,15)
    override def receive: Actor.Receive = {
      case Print(x) if x < 5=> println(s"${self.path}: ${seq(x)}")
        sender() ! Print(x+1)
    }

  }

  val system = ActorSystem("work")
  val work1 = system.actorOf(Props[WorkActor1],name = "work1")
  val work2 = system.actorOf(Props[WorkActor2],name = "work2")
  work1 ! Print(0)
}

这边也简单实现一个,其实是不建议直接在work1中设置work2,更好的做法是path或者actorref传进去,当时为了简单就这样实现了一下,最近在翻译akka stream的官方doc
地址是
akka stream中文链接

我的github

你可能感兴趣的:(多线程,akka)