Java static synchronization method

What happens when two threads call static synchronization methods with different instances at the same time? Is it possible? Object locks are used for non statically synchronized methods, but what types of locks are used for statically synchronized methods?

Solution

It is the same as synchronizing on the class object implementing the method, so yes, it is possible, and yes, the mechanism effectively ignores the instance calling the method:

class Foo {
    private static synchronized doSomething() {
        // Synchronized code
    }
}

Is a shortcut to write this:

class Foo {
    private static doSomething() {
        synchronized(Foo.class) {
            // Synchronized code
        }
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>