[关闭]
@xtccc 2016-12-30T14:06:39.000000Z 字数 1155 阅读 1633

Concurrency & Synchronization

给我写信
GitHub

此处输入图片的描述

Scala


参考:
+ Thread Safety Problem
+ Concurrency in Scala




目录


1. 利用future并发执行


  1. object TestSynchronize extends App {
  2. val factory = new Factory()
  3. val f: IndexedSeq[Future[Unit]] =
  4. for (i <- 0 until 10) yield Future {
  5. factory.m1(i)
  6. }
  7. val sequence: Future[IndexedSeq[Unit]] = Future.sequence(f)
  8. Await.result(sequence, 30 seconds)
  9. println("全部结束")
  10. }
  11. class Factory {
  12. def m1(x: Int): Unit = {
  13. println(s"进入: $x")
  14. Thread.sleep(Math.abs(Random.nextInt()) % 2 * 1000)
  15. println(s"离开: $x\n")
  16. }
  17. }



运行结果:

进入: 2
进入: 3
进入: 4
进入: 1
进入: 6
进入: 7
进入: 0
进入: 5
离开: 1

进入: 8
离开: 8

进入: 9
离开: 2

离开: 3

离开: 5

离开: 4

离开: 7

离开: 9

离开: 6

离开: 0

全部结束



可以,以上是并发运行的,所以打印出的内容是乱序的。




2. 互斥


可以通过 synchronized 关键字实现互斥访问

  1. object TestSynchronize extends App {
  2. val factory = new Factory()
  3. val f: IndexedSeq[Future[Unit]] =
  4. for (i <- 0 until 10) yield Future {
  5. factory.m1(i)
  6. }
  7. val sequence: Future[IndexedSeq[Unit]] = Future.sequence(f)
  8. Await.result(sequence, 30 seconds)
  9. println("全部结束")
  10. }
  11. /**
  12. * 要求, 方法Factory.produce不能同时被多个线程访问
  13. * 换句话说,它必须是thread-safety method
  14. * */
  15. class Factory {
  16. def m1(x: Int): Unit = this.synchronized {
  17. println(s"进入: $x")
  18. Thread.sleep(Math.abs(Random.nextInt()) % 2 * 1000)
  19. println(s"离开: $x\n")
  20. }
  21. }

运行结果:

进入: 0
离开: 0

进入: 7
离开: 7

进入: 9
离开: 9

进入: 6
离开: 6

进入: 5
离开: 5

进入: 4
离开: 4

进入: 3
离开: 3

进入: 1
离开: 1

进入: 2
离开: 2

进入: 8
离开: 8

全部结束

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注