加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 锁定类的静态成员

发布时间:2020-12-14 23:43:50 所属栏目:Java 来源:网络整理
导读:根据我的理解,下面的代码应该导致死锁. 原因是,当线程t1锁定静态对象firstData时,他已经获得了对类的锁定.因此,当他试图锁定另一个静态对象secondData时,请求应该阻塞. 但是,程序运行正常并打印***成功获得了两个锁 锁定静态对象的原因是什么? public class
根据我的理解,下面的代码应该导致死锁.
原因是,当线程t1锁定静态对象firstData时,他已经获得了对类的锁定.因此,当他试图锁定另一个静态对象secondData时,请求应该阻塞.

但是,程序运行正常并打印***成功获得了两个锁

锁定静态对象的原因是什么?

public class Deadlock {
    public static void main(String[] args) {

        Thread t1 = new Thread(new DeadlockRunnable());
        t1.start();
    }
} 

 class DeadlockRunnable implements Runnable {
    static  Object firstData = new Object();
    static  Object secondData = new Object();

    public void run() {
        synchronized(firstData) {
            synchronized(secondData) {
                System.out.println("*** Successfully acquired both the locks");
            }
        }
    }

}

对于那些回答锁是对象而不是课堂的人,请看一下this

解决方法

首先,你有一个错误:

The reason being,when thread t1 locks static object firstData,he has acquired a lock on the class.

锁定静态对象仅锁定该对象,而不是类.您正在锁定两个单独的对象.

question you refered to大约是synchronized methods而不是synchronized statements.这两个相关结构的工作方式略有不同.

其次,即使您锁定了同一个对象,您的代码仍然不会死锁(ideone).内在锁是可重入的.这意味着如果线程尝试两次使用相同的锁,则线程不会自行死锁.

Reentrant Synchronization

Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code,directly or indirectly,invokes a method that also contains synchronized code,and both sets of code use the same lock. Without reentrant synchronization,synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.

Source

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读