gpt4 book ai didi

multithreading - Scala:唤醒 sleep 线程

转载 作者:行者123 更新时间:2023-12-03 13:16:07 28 4
gpt4 key购买 nike

在scala中,我如何告诉线程: sleep t秒钟,或直到收到消息?也就是说,最多只能睡t秒钟,但是如果t尚未结束,您会醒来,并且您会收到一条特定的消息。

最佳答案

或者,您可以使用条件变量。

val monitor = new AnyRef
var messageReceived: Boolean = false

// The waiting thread...

def waitUntilMessageReceived(timeout: Int): Boolean = {
monitor synchronized {
// The time-out handling here is simplified for the purpose
// of exhibition. The "wait" may wake up spuriously for no
// apparent reason. So in practice, this would be more complicated,
// actually.
while (!messageReceived) monitor.wait(timeout * 1000L)
messageReceived
}
}

// The thread, which sends the message...

def sendMessage: Unit = monitor synchronized {
messageReceived = true
monitor.notifyAll
}

关于multithreading - Scala:唤醒 sleep 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15635011/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com