Is the this
and Example.this
the same object?
Eg Is the call this
and Example.class
inside the synchronized
the same object?
class Example {
public Example() {
synchronized(this) {
// some code
}
}
}
class Example {
public Example() {
synchronized(Example.class) {
// some code
}
}
}
不, this
使用当前对象作为监视器,但是Example.class
使用Example.class
作为监视器。
不, this
是Example
的实例,而Example.class
是Class
的实例。
No.
Synchronizing on this
is instance-level locking, meaning that the critical section cannot be re-entered with same object.
Synchronizing on Example.class
is class-level locking, meaning that no other instance of the class, including this
, can enter that critical section.
As you can see, class-level locking is, in a sense, more drastic.
This will synchronize access to the locked class instead of the this/current object. Use whichever you find easier and more effective.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.