Java Thread Locks [closed]
开发者_C百科
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this questionIf a running thread access a specific object thus it also held lock on the field members of that specific object?
Are you explicitly locking on the object? Are you using synchronized
?
Having a lock on an object does not imply having a lock on its members.
Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. (The API specification often refers to this entity simply as a "monitor.") Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.
- Read More
A lock is just a lock, and the only thing it guarantees is that only one thread at once can have it. It is up to you to write the code that ensures that the things you want locked are in fact locked.
So if you write:
class MyClass {
private int myvalue;
public synchronized void setValue(int newvalue) {
myvalue = newvalue;
}
}
then you ensure that only one thread at once can be writing to myvalue. However if you were to make myvalue public or provide another way of writing to it, then nothing is preventing other threads from simultaneously writing to myvalue. Coding the logic is up to you.
If you are locking on the object in question then another thread could not obviously obtain the lock however that does not restrict the field members from being changed or modified.
精彩评论