1 回答
TA贡献1906条经验 获得超10个赞
有几个问题:
你应该使用
start
on notrun
。如果您正在使用
join
,则将踏面设置为守护线程是没有意义的。当您
if ... else
在生产商中进行操作时,您只会得到奇数。它应该只是if
和其余的if
(实际上while
是一个更好的做法)。
我认为这样代码可以满足您的需求:
object ThreadsMain extends App {
val syncVar = new SyncVar[Int]()
val isDone = new AtomicBoolean(false)
val producer = new Thread {
override def run(): Unit = {
for (x <- 1 to 15) {
syncVar.synchronized {
while (!syncVar.isEmpty) {
syncVar.wait()
}
syncVar.put(x)
syncVar.notify()
}
}
isDone.set(true)
}
}
producer.start()
val consumer = new Thread {
override def run(): Unit = {
while (!isDone.get()) {
syncVar.synchronized {
while (syncVar.isEmpty) {
syncVar.wait()
}
println(syncVar.get())
syncVar.notify()
}
}
}
}
consumer.start()
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
}
}
}
添加回答
举报