In general, two threads can run two methods at the same time; however, in your example, only one thread can run f() or g() at any time.
Using the synchronized changes the interaction of threads. Each Java object has a lock, an element that can contain only one thread at a time. synchronized is a command that directs threads to obtain a lock before executing a method and releases it after that. The lock is maintained during the entire execution of the method.
In your example, only one thread will execute f() or g() at any given time, because the βotherβ thread will wait its turn to capture the lock.
If you have two objects of the same class, you have two locks. This means that you can get two threads to run f() and g() at the same time with the synchronized keywords without changes, since the threads will capture locks on different objects. You simply cannot force threads to run simultaneously on the same object without removing the synchronized .
Edwin buck
source share