Java同步和静态同步方法访问静态字段 [英] Java synchronized and static synchronized method accessing static field

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

问题描述

以下程序的行为是什么,其中静态同步方法和实例同步方法试图访问不同线程中同一类的静态字段?任何线程都会被阻塞吗?它非常令人困惑.

What would be the behaviour of the following program where static synchronized method and instance synchronized method is trying to access static field of same class in different threads? Will any thread get blocked? Its very confusing.

class MyClass
{
        public static int i = 5;

        public synchronized void m1()
        {
                System.out.println(i); //uses static field i of MyClass
            //T1 is executing this method
        }

        public static synchronized void m3()
        {
            //T2 will be able to call this method on same object lock while it is using
            //static field i???
            System.out.println(i);//uses static field i of MyClass
        }
}

推荐答案

同步实例方法等价于

public void m1() {
    synchronized(this) {
        ...
    }
}

(好吧,它们并不完全相同,但您的问题的答案不会受到这种差异的影响).

(well, they are not exactly the same, but the answer to your question does not suffer from that difference).

同步的静态方法在类上同步:

Synchronized static methods are synchronized on the class:

public void m2() {
    synchronized(MyClass.class) {
        ...
    }
}

如您所见,两个块在不同的对象上同步:m1 在调用它的实例上同步,m2 在<的实例上同步code>Class 代表您在 JVM 中的类.所以这两个方法可以被调用而不会互相阻塞.

As you can see, two block are synchronized on difference objects: m1 is synchronized on the instance it is called on, and m2 is synchronized on the instance of Class<MyClass> which represents your class in JVM. So those two methods can be called without blocking each other.

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

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