Lock and Synchronized keywords
In order to synchronize multiple threads, the Java language uses a monitor (monitors), an advanced mechanism to qualify only one thread at a time to execute a piece of code that is protected by the monitor. The behavior of the monitor is implemented by locks, and each object has a lock.
Each thread has a working memory that is stored in a variable copied from the main memory shared by all threads. To access a shared variable, a thread usually first obtains a lock and refreshes its working memory, which copies the shared value from main memory to working memory. When the line threads unlocked, the values in the working memory will be written back to the main memory.
&n BSP; A line Cheng Nen gets the lock of the object multiple times. That is, one synchronized method invokes another synchronized method, and the latter calls another synchronized method, and so on. The JVM keeps track of how many objects are locked. If the object is not locked, then its counter should be zero. When a thread first obtains a lock on an object, the counter is one. Each time the thread receives a lock on the object, the counter adds one. Of course, only the thread that gets the object lock for the first time can get the lock more than once. Each step of the thread exits a synchronized method, and the counter is reduced by one. When it is zero, the object is unlocked, and other threads can use the object.
In addition, each class has a lock (which belongs to the class object) so that when the synchronized static method of the class reads the static data, it does not interfere with each other.
Threads do not interact directly with each other, they communicate only through main memory.
starting with J2SE 1.5, Java has a lock interface that makes the concept of locks clearer, making it easier to control thread synchronization. With synchronized, you cannot control the release of the lock, and with the lock interface you will be able to lock () or unlock () as you need.