java静态同步方法 [英] java static synchronized method

查看:78
本文介绍了java静态同步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当两个线程同时使用不同的实例调用静态同步方法时会发生什么?可能吗?对象锁用于非静态同步方法但是什么类型的锁用于静态同步方法?

What happens when a static synchronized method is called by two threads using different instances at the same time? Is it possible? The object lock is used for non static synchronized method but what type lock is used for static synchronized method?

推荐答案

它是一样的在实现该方法的 Class 对象上进行同步,是的,这是可能的,是的,该机制有效地忽略了调用该方法的实例:

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 fro which the method is called:

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

是写这个的快捷方式:

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

这篇关于java静态同步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆