Lock on an object that might change during code execution
问题 Let's suppose I have a thread that locks on an object reference Thread #1 lock(myObj) { ... } later in code I have myObj = new XYZObj(); and then Thread #2 locks on it lock(myObj) { ... } Will this code be thread safe, if the object reference has changed? When the object reference changes, the first lock is still valid? 回答1: Locks work on instances, not variables. The lock statement will hold its own reference to the instance so that it will only exit the instance you entered. The spec says: