scala/ScalaBook/chapter-07/syncCell-v2.scala
import concurrent.MailBox
//import concurrent.ops
class cell (protected var contents : Int){
private val mbox = new MailBox
private case class Empty()
private case class Full(n : Int)
mbox send Full(contents) // initialize
def get() : Int =
mbox receive {
case Full(n) =>
mbox send Empty()
n
}
def set(n: Int) : Unit =
mbox receive {
case Empty() =>
mbox send Full(n)
}
}
class doubleCell(c : cell) extends Runnable {
override def run(): Unit = {
for ( i <- 1 to 10) {
var v = c.get
println("D---> got "+v)
c.set(2*v)
println("D---> send "+(2*v))
}
return
}
}
class halveCell(c : cell) extends Runnable {
override def run(): Unit = {
var v = c.get
for ( i <- 1 to 10) {
c.set(v/2)
println("H---> send "+(v/2))
v = c.get
println("H---> got "+v)
}
return
}
}
object threadExample4 {
def main(args: Array[String]) {
var c = new cell(16)
new Thread(new doubleCell(c)).start()
new Thread(new halveCell(c)).start()
}
}