根据这个文件,在Kotlin中使用wait和notify不鼓励:https://kotlinlang.org/docs/reference/java-interop.html
等待()/通知()
有效的Java Item 69建议更喜欢并发实用程序来wait()和notify().因此,这些方法不适用于Any类型的引用.
但是,该文件没有提出任何正确的方法.
基本上,我想实现一个服务,它将读取输入数据并处理它们.如果没有输入数据,它将暂停,直到有人通知有新的输入数据.就像是
while (true) {
val data = fetchData()
processData(data)
if (data.isEmpty()) {
wait()
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
我不想使用这些不推荐的方法(反模式),我真的想知道如何正确地做到这一点.
在我的情况下fetchData从数据库中读取数据,因此在我的情况下不能使用队列.
我有一个用例,我需要连接和断开作为服务的类。只有在服务连接时才能对服务执行操作。当服务连接或断开时通过回调通知客户端:
class Service {
constructor(callback: ConnectionCallback) { ... }
fun connect() {
// Call callback.onConnected() some time after this method returns.
}
fun disconnect() {
// Call callback.onConnectionSuspended() some time after this method returns.
}
fun isConnected(): Boolean { ... }
fun performAction(actionName: String, callback: ActionCallback) {
// Perform a given action on the service, failing with a fatal exception if called when the service is not connected.
}
interface ConnectionCallback {
fun onConnected() // May be called multiple times …Run Code Online (Sandbox Code Playgroud)