kotlin 对象锁

kotlin object lock

我想在 Kotlin 中使用同步(对象锁),但不知道如何在 Kotlin 中使用同步。我已经在 Kotlin 搜索了同步的用法,但 ReentrantLock 无法锁定我猜想的对象。请帮助我,我在 2 天前遇到了这个问题。

    override fun run() {
        var active = false
        while (true) {
            while (queue.isEmpty()) {
                if (!running) {
                    return
                }
                synchronized(this) {
                    try {
                        active = false
                        wait() //<< here's error

                    } catch (e: InterruptedException) {
                        LogUtils.getLogger()
                            .log(Level.SEVERE, "There was a exception with SQL")
                        LogUtils.logThrowable(e)
                    }
                }
            }
            if (!active) {
                con.refresh()
                active = true
            }
            val rec = queue.poll()
            con.updateSQL(rec.getType(), *rec.getArgs())
        }
    }

    /**
     * Adds new record to the queue, where it will be saved to the database.
     *
     * @param rec Record to save
     */
    fun add(rec: Record) {
        synchronized(this) {
            queue.add(rec)
            notifyAll() //<< here's too
        }
    }

    /**
     * Ends this saver's job, letting it save all remaining data.
     */
    fun end() {
        synchronized(this) {
            running = false
            notifyAll() //<< and here
        }
    }```

嗯,Correctly implementing wait and notify in Kotlin中提到的解决方案在这里也行得通。将 wait() //<< here's error 替换为 (this as Object).work() 并将 notifyAll() //<< and here 替换为 (this as Object).notifyAll() 将导致与 Java 相同的行为。