I have a Res class that contains a synchronized method A and an unsynchronized method B. In another class, I create an instance of the Res class and two threads: I assign the synchronization method A to the Res class for the first thread and assign the unsynchronized method B to the second thread for the same instance of Res. From the literature, I realized that if a synchronized method gets control, the calling thread activates a monitor that blocks an object for other threads, that is, in my example, you must first fully work out method A, and only then method B. However, I checked and it turns out that For some reason, B works in parallel with method A. If I make method B also synchronized, then this parallelism disappears. It turns out that if a synchronized method was invoked for an object in one thread, then an unsynchronized method can run in parallel for another object for the same object? That is, the possibility of executing for an object from another thread only synchronized methods is blocked, and unsynchronized methods can be executed?
public class Res { int number = 0; public synchronized void A(){ for (int i = 0; i<10000; i++) { number += 1; System.out.println(number); } } public void B(){ for (int i = 0; i <10000; i++) number-=1; } } public class Threads { Res commonRes = new Res(); public void startThreads(){ new Thread(()->commonRes.A()).start(); new Thread(()-> commonRes.B()).start(); } }