Locks act as a tool for concurrent shared data, ensuring consistency, and there are many implementations in the Java platform, such assynchronizedand Reentrantlock, etc.). These locks have been written to provide convenience for our development, but the specific nature and type of the lock are rarely mentioned. This series of articles will analyze common lock names and features in Java to help you answer questions. Four, can be re-entry lock: This article is about the generalized can be re-entry lock, rather than single-finger Java reentrantlock. A reentrant lock, also called a recursive lock, means that the inner recursive function still has the code to acquire the lock after the same thread's outer function acquires the lock, but is unaffected. Both Reentrantlock and synchronized are reentrant locks in the Java environment. Here is the usage example: Copy code code as follows: Public classTestImplementsrunnable{ Public synchronized voidget () {System.out.println (Thread.CurrentThread (). GetId ()); Set (); } Public synchronized voidset () {System.out.println (Thread.CurrentThread (). GetId ());} @Override Public voidrun () {get ();} Public Static voidMain (string[] args) {Test ss=NewTest (); NewThread (ss). Start (); NewThread (ss). Start (); NewThread (ss). Start ();}} Two examples The final result is correct, that is, the same thread ID is continuously output two times. The results are as follows: The copy code code is: Threadid:8Threadid:8Threadid:10Threadid:10Threadid:9Threadid:9the maximum effect of reentrant locks is to avoid deadlocks. We use spin locks as an example. Copy the code code as follows: Public classSpinLock {PrivateAtomicreference<thread> owner =NewAtomicreference<>(); Public voidLock () {Thread current=Thread.CurrentThread (); while(!owner.compareandset (NULL, current)) { } } Public voidunlock () {Thread current=Thread.CurrentThread (); Owner.compareandset (Current,NULL); }} for spin locks:1, if the same thread two call lock (), will cause the second call to the lock position spin, resulting in a deadlock indicates that the lock is not reentrant. (Within the lock function, you should verify that the thread is the thread that has acquired the lock)2, if the 1 problem is resolved, the lock is released when Unlock () is first called. You should not actually release the lock. After the modification, as follows: Copy the code code as follows: Public classSpinLock1 {PrivateAtomicreference<thread> owner =NewAtomicreference<>(); Private intCount =0; Public voidLock () {Thread current=Thread.CurrentThread (); if(current==Owner.get ()) {Count++; return ; } while(!owner.compareandset (NULL, current)) { } } Public voidunlock () {Thread current=Thread.CurrentThread (); if(current==Owner.get ()) { if(count!=0) {Count--; }Else{Owner.compareandset (current,NULL); } } }}
Java can be re-entered lock