在 C# 中,它非常简单:
class Class1{
private static readonly object locker = new object();
void Method1(){
lock(locker) { .... }
}
}
而且我绝对不应该进行同步,this
因为它可能会导致死锁。同样,在 Scala 中,我看到了一些示例,但无法理解同步的基本原理和我应该用来进行同步的对象(字段)是什么:
#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...
你介意给我说清楚吗?