java – 锁定类的静态成员

前端之家收集整理的这篇文章主要介绍了java – 锁定类的静态成员前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
根据我的理解,下面的代码应该导致死锁.
原因是,当线程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

猜你在找的Java相关文章