Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1520001
  • 博文数量: 399
  • 博客积分: 8508
  • 博客等级: 中将
  • 技术积分: 5302
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-14 09:28
个人简介

能力强的人善于解决问题,有智慧的人善于绕过问题。 区别很微妙,小心谨慎做后者。

文章分类

全部博文(399)

文章存档

2018年(3)

2017年(1)

2016年(1)

2015年(69)

2013年(14)

2012年(17)

2011年(12)

2010年(189)

2009年(93)

分类: 架构设计与优化

2015-05-02 00:33:36

package STM
import scala.concurrent.stm.Ref
import scala.concurrent.stm.atomic
import scala.concurrent.stm.retry
import scala.concurrent.stm.retryFor
import java.util.Timer
import java.util.TimerTask
import java.util.concurrent.TimeUnit

object SensibleWait {

  val start = System.nanoTime()

  val cups = Ref(24)

  def fillCup(numberOfCups: Int) = {

    atomic {
      implicit tx =>
        {
          if (cups() < numberOfCups) {
            println("retry........ at " + (System.nanoTime() - start) / 1.0e9)
            retryFor(5, TimeUnit.SECONDS)
          }
          cups.swap(cups() - numberOfCups)
          println("Fill up ... " + numberOfCups)
          println("........ at " + (System.nanoTime() - start)/1.0e9)
        }
    }
  }

  def main(args : Array[String]) = {
    val timer = new Timer(true)
    
    timer.schedule(new TimerTask() {
      def run() {
        println("Refilling.... at " + (System.nanoTime() - start)/1.0e9)
        atomic {
          implicit tx => cups() = 24
        }
      }
    }, 5000)
    
    SensibleWait.fillCup(20)
    SensibleWait.fillCup(10)
    try {
      SensibleWait.fillCup(22)
    } catch {
      case ex : Throwable => println("Failed: " + ex.getMessage())
    }
    println("Ending.....")
  }
 
}
阅读(762) | 评论(0) | 转发(0) |
0

上一篇:Actor 生命周期

下一篇:Scala 基础回顾

给主人留下些什么吧!~~