Are the following two Synchronize blocks mutually exclusive?

Object obj=new Object();
Object obj2=obj;
synchronized(obj){}
synchronized(obj2){}

what if this is the case?

Object obj=new Object();
synchronized(obj){}
obj=new Object();
synchronized(obj){}

the above two synchronized blocks are mutually exclusive.
so based on the fact that this lock object may be misused, it is recommended to use a separate final object as the lock instead of the business-related variable:


:synchronized(obj){}objobjobjsynchronized(obj){}

:

    static Object obj=new String("a");
    public static void main(String[] args) throws InterruptedException {
        class a extends Thread{
            @Override
            public void run() {
                synchronized(obj){
                    for (int i = 0; i < 10000; iPP) {
                        if(i%10==0)System.out.println(obj+",0");
                    }
                }
            }
        }
        new a().start();
        Thread.sleep(10);
        obj=new String("b");
        class b extends Thread{
            @Override
            public void run() {
                synchronized(obj){
                    for (int i = 0; i < 10000; iPP) {
                        if(i%10==0)System.out.println(obj+",1");
                    }
                }
            }
        }
        new b().start();
    }

Test results: if the output of two threads is crossed, Synchronize will indeed fail

Menu