简体   繁体   中英

Difference between synchronized

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作为监视器。

不, thisExample的实例,而Example.classClass的实例。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM