Can synchronized methods run simultaneously?

I created 2 objects and 2 threads. Suppose that m1 () and m2 () are synchronized methods.

t1.m1 (); t2.m2 (); can both threads run simultaneously? is it possible to simultaneously execute both synchronized methods?

+3
source share
5 answers

Synchronization occurs in certain cases. Synchronized methods synchronize in instances invoked by the method. Thus, t1.m1()they t2.m2()can be performed simultaneously, if and only if t1they t2relate to different instances.

+2
source

Yes, if both are non-static and run using two different instances.

.

monitor . , , .

+1

, .

synchronized void someMethod(){
}

void someMethod(){
   synchronized(this){
   }
}

, .

(SomeClass.class).

+1

, , .

0

. .

When you synchronize, the monitor is either an object (non-static) or a Class object (static methods).

You have to think about

public synchronized void myMethod(){
  ...
}

as:

public void myMethod(){
  synchronized (this) {
    ...
  }
}

Since you have two independent instances of an object with a synchronized method, you have 2 different monitors. Result: both threads can work simultaneously.

0
source

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


All Articles