Why Thread Does Not Release Lock When Link Changes

public class UThread implements Runnable {

    Object o;

    UThread(Object o) {
        this.o = o;
    }

    @Override
    public void run() {
        synchronized (o) {
            System.out.println("inside before change" + Thread.currentThread().getName());
            try {
                Thread.sleep(5000);
            } catch (Exception er) {
            }
            o = new Object();
            System.out.println("inside after change" + Thread.currentThread().getName());
            try {
                Thread.sleep(5000);
            } catch (Exception er) {
            }

        }
        System.out.println("outside " + Thread.currentThread().getName());

    }


}


public class main {
    public static void main(String str[]) {

        Object o = new Object();
        UThread uThread = new UThread(o);
        Thread th = new Thread(uThread);

        UThread uThread2 = new UThread(o);
        Thread th2 = new Thread(uThread2);

        th.start();
        try {
            Thread.sleep(1000);
        } catch (Exception er) {
        }
        th2.start();
    }
}

When we execute the code, it prints

inside before changingThread-0
inside after changeThread-0
outside topic -0
inside before changeThread-1
inside after changeThread-1
outside topic-1

So, why the second thread did not take the lock on owhen the object changed.

+4
source share
2 answers

Link assignment does nothing for the base object. All this makes a copy of the reference value without touching or changing the object itself. For example, it does not block the lock and should not.

eg.

Object o2 = o;
synchronized(o) {
    o = new Object();
    // o2 is still locked
}
// o2 is not locked
+4
source

, o ( UThread).

o , , o, .

+1

Source: https://habr.com/ru/post/1684203/


All Articles