简体   繁体   中英

Calling synchronized method with two different references of the object of the same class

I have a synchronised method and I want to call it using two different instance of the same class. I am not able to understand what exactly will happen here. And if there's a way to force these calls to execute one after another?

Code

public class A1 {

    public synchronized void m1(){

        try{
            
            Thread.sleep(5000);

        }catch(Exception e){

        }
    }


    public static void main(String[] args) {
        A1 o1 = new A1();
        A1 o2 = new A1();
        o1.m1();
        o2.m1();
    }
}

The synchronized keyword synchronizes the access to the method locking onto the object on which the method is called. This means that two thread calling the method on the same object will execute one after the other, while two thread calling that method on two different object will execute concurrently.

If you want to synchronize the calls even in the latter case, you can synchronize on a different object which is accessible to both threads. This is usually done synchronizing on a Class object:

public class A1 {
    public void m1() {
        synchronized(A1.class) {
            try {
                Thread.sleep(5000);
            } catch(final Exception e) {
                e.printStackTrace();
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM