Why can't you create a deadlock if you delete static in this deadlock problem?

topic description

this code can be executed, but I delete static Object o1 = new Object (), o2 = new Object (); before the static, deadlock problem is gone.

related codes

public class TestDeadLock implements Runnable {
    int flag = 1;
    static Object o1 = new Object(), o2 = new Object();

    public static void main(String[] args) {
        TestDeadLock tdl1 = new TestDeadLock();
        TestDeadLock tdl2 = new TestDeadLock();
        tdl1.flag = 0;
        tdl2.flag = 1;
        Thread t1 = new Thread(tdl1);
        Thread t2 = new Thread(tdl2);
        t1.start();
        t2.start();
    }

    @Override
    public void run() {
        System.out.println("flag:" + flag);
        if (flag == 0) {
            synchronized (o1) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    // TODO: handle exception
                }
                synchronized (o2) {
                    System.out.println("0");
                }
            }
        }
        if (flag == 1) {
            synchronized (o2) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    // TODO: handle exception
                }
                synchronized (o1) {
                    System.out.println("1");
                }
            }
        }
        
    }
}
Mar.28,2021

if you do not add static, then tdl1 and tdl2 have their own o1 and O2 respectively, so there is no deadlock


because after you use static decoration, the two instances of o1o2 are static instances (created when the class is loaded), no matter how many TestDeadLock objects you create, they are the same, so different TestDeadLock capabilities will cause lock waiting when accessing, resulting in deadlock.
but if you remove the o1 and O2 attributes here in static, so when you new different TestDeadLock objects, they are actually different objects and are not affected at all (although the code level looks like o1o2, but when the actual program runs, the o1o2 of tdl1 is different from that of tdl2, which has nothing to do with each other.)

Menu