在 Scala 中同步哪个对象?
2022-09-03 09:01:25
在C#中,它非常简单:
class Class1{
private static readonly object locker = new object();
void Method1(){
lock(locker) { .... }
}
}
而且我绝对不应该进行同步,因为它可能会导致死锁。同样,在Scala中,我看到了一些例子,但无法理解我应该用来进行同步的同步和对象(场)的基本原理是什么:this
#1
def add(user: User) {
// tokenizeName was measured to be the most expensive operation.
val tokens = tokenizeName(user.name)
tokens.foreach { term =>
userMap.synchronized {
add(term, user)
}
}
}
#2
class Person(var name: String) {
def set(changedName: String) {
this.synchronized {
name = changedName
}
}
}
#3 and so on...
你介意为我说清楚吗?