我对 Java 并发非常陌生,并且在尝试使用锁和监视器编写玩具问题时陷入困境。问题的要点是,我有一个具有get和put方法的类,并且本质上是线程消费和生产的容器。对于我的生活,我无法正确同步,最终会出现死锁或IllegalMonitorStateException.
package concurrency
object ThreadsMain extends App {
val syncVar = new SyncVar[Int]()
val producer = new Thread {
override def run(): Unit = {
for (x <- 1 to 15) {
syncVar.synchronized {
if (!syncVar.isEmpty) {
syncVar.wait()
} else {
syncVar.put(x)
syncVar.notify()
}
}
}
}
}
producer.run()
val consumer = new Thread {
this.setDaemon(true)
override def run(): Unit = {
while (true) {
syncVar.synchronized {
if (syncVar.isEmpty) {
syncVar.wait()
} else {
println(syncVar.get())
syncVar.notify()
}
}
}
}
}
consumer.run()
producer.join()
consumer.join()
}
class SyncVar[T]() {
var isEmpty: Boolean = true
var value: Option[T] = None
def get(): T = {
if (isEmpty) throw new Exception("Get from empty SyncVar")
else {
val toReturn = value.get
value = None
isEmpty = true
toReturn
}
}
def put(x: T): Unit = {
if (!isEmpty) throw new Exception("Put on non-empty SyncVar")
else {
value = Some(x)
isEmpty = false
}
}
}
隔江千里
相关分类