Skip to content

Instantly share code, notes, and snippets.

@ee7klt
Created January 17, 2017 04:27
Show Gist options
  • Save ee7klt/f2c87f65cab186a8c00e9d013692c532 to your computer and use it in GitHub Desktop.
Save ee7klt/f2c87f65cab186a8c00e9d013692c532 to your computer and use it in GitHub Desktop.
parallelism on the jvm ii
class Account(private var amount: Int = 0) {
def transfer(target:Account, n: Int) =
this.synchronized {
target.synchronized {
this.amount -= n
target.amount += n
}
}
}
def startThread(a: Account, b: Account, n: Int) = {
val t = new Thread {
override def run() {
for (i <- 0 until n) {
a.transfer(b,1)
}
}
}
t.start()
t
}
val a1 = new Account(500000)
val a2 = new Account(700000)
val t = startThread(a1, a2, 150000)
vat s = startThread(a2, a1, 150000)
t.join()
s.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment