Java 中没有主对象的同步块
Synchronized block in Java without main Object
我想知道为什么 Java 需要 synchronized
块中的对象。即:
synchronized(object) {
// stuff
}
为什么我不能在不指定任何对象的情况下使用简单块?例如:
synchronized {
// stuff
}
根据 documentation:
内部锁和同步
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.
Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them.
同步语句
Another way to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock.
我想知道为什么 Java 需要 synchronized
块中的对象。即:
synchronized(object) {
// stuff
}
为什么我不能在不指定任何对象的情况下使用简单块?例如:
synchronized {
// stuff
}
根据 documentation:
内部锁和同步
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. Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them.
同步语句
Another way to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock.