我有一个可变的可为空属性。我想检查一个方法的值是否为空,如果是,请将其设置为新创建的对象。然后我会调用属性的方法(旧的或新的,但现有的对象)。
这应该是线程安全的。我怎样才能在 Kotlin 中做到这一点?
与 .let
,我无法重新分配该属性。使用 synchronized(...)
时或 .withLock
,在赋值和调用之间,线程可以被另一个中断。或者至少 IDE 这么说,智能转换是不可能的。我不明白,为什么是synchronized
如果它不同步块(synchronized block)呢?
var starterTask: AsyncTask<MyData, Void, Void>? = null
fun start() {
make it thread safe {
if (starterTask == null) {
starterTask = a child of AsyncTask()
}
starterTask.execute(this) // <- no !! operator
}
}
在 Java 中,如果我用
synchronized
锁定了一个对象,我可以检查、分配、调用一个对象,每个人都很高兴。我可以在 Kotlin 中做同样的事情吗?
最佳答案
您可以使用 delegated property为了那个原因:
val starterTask = lazy { a child of AsyncTask() }
fun start() {
starterTask.execute(this)
默认线程安全模式是
SYNCHRONIZED
,所以它符合您的需求。
关于asynchronous - 如何在 Kotlin 中同步检查和设置变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58905102/