Skip to content

Instantly share code, notes, and snippets.

@kghost
Created Mar 21, 2019
Embed
What would you like to do?
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