Skip to content

Instantly share code, notes, and snippets.

@kghost
Created March 21, 2019 11:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kghost/585cb0d2f1c66ebc7d9af3d0a4fd8a42 to your computer and use it in GitHub Desktop.
Save kghost/585cb0d2f1c66ebc7d9af3d0a4fd8a42 to your computer and use it in GitHub Desktop.
val s = Array("A", "B", "C")
val lock = new java.util.concurrent.locks.ReentrantLock()
val total = s.length
var token: Int = 0
val cvs = s.map(i => lock.newCondition())
val threads = for (t <- 0 until 3) yield {
val thread = new Thread {
override def run {
lock.lock()
for (i <- 0 until 10) {
while (token != t) cvs(t).await()
println(s(t))
token = (token + 1) % total
cvs(token).signal()
}
lock.unlock()
}
}
thread.start()
thread
}
for (thread <- threads) thread.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment