Multi-threaded knowledge combing (2) basic use of synchronized trilogy
1. Why use synchronized The reason for using synchronized is that : it can ensure that multiple threads can only have one at the same time, The thread is in a method or synchronization block,It guarantees the visibility and exclusivity of the thread’s access to variables. Second, the principle of synchronized Before JDK 1.6 ,synchronized is implemented based on object monitoring , This is also known as a weight lock. By default ,Each object has an associated Monitor, and each Monitor contains an EntryCount counter ,It is the key for synchronized to achieve reentrancy. After JDK 1.6 , a series of optimization measures for locks , by introducing spin locks, adaptive spin locks, lock elimination, Lock coarsening, biased locks, lightweight locks and other technologies to reduce the overhead of lock operations. The ultimate goal of these optimization measures is to reduce the overhead of lock operations ,However, what it changes is only the way the lock is implemented,But the basic principle of locking and unlocking has not changed . This article mainly introduces the use of synchronized,so,in the following introduction,we still analyze it in the way of weight lock which is easier to understand, ;In a later article,let’s talk about…