Java – lock static members of a class

According to my understanding, the following code should cause deadlock

However, the program runs normally and prints * * * successfully obtained two locks

What is the reason for locking static objects?

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");
            }
        }
    }

}

For those who answer that the lock is the object rather than the classroom, please take a look at this

Solution

First, you have a mistake:

Locking a static object locks only the object, not the class You are locking two separate objects

Question you referred to is about synchronized methods instead of synchronized statements The two related structures work slightly differently

Second, even if you lock the same object, your code will not deadlock Internal locks are reentrant This means that if a thread tries to use the same lock twice, the thread will not deadlock itself

Source

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
分享
二维码
< <上一篇
下一篇>>