40 threads (XII) - ReentrantLock reentrant lock

synchronized plus locks we are using can continue to use, as follows:

Test void public () { 
	 // get the first lock 
	 the synchronized (the this) { 
		 the while (to true) { 
			 // get the same second locking 
			 the synchronized (the this) { 
				 System.out.println ( "of ReentrantLock"); 
			 } 
			 the try { 
				 the Thread.sleep (1000); 
			 } the catch (InterruptedException E) { 
				 // the TODO Auto-Generated Block the catch 
				 e.printStackTrace (); 
			 } 
		 } 
	 } 
 }

  

Plus the use of synchronized lock must wait until the end of the thread will be released, which may cause a deadlock.

The relatively synchronized, ReentrantLock lock is more flexible, it can be specified lock after a period of time the initiative to release the lock and so much more powerful now you can only do understand.

Details on their own Baidu. Next parodies ReentrantLock source code, to achieve the basic lock and unLock method.

_20191209 Package; 
/ ** 
 * Demo reentrant lock: locks do not continue to use 
 * @author TEDU 
 * 
 * / 
public class LockTest03 { 
	relock = new new relock Lock (); 
	public void A () throws InterruptedException { 
		Lock.lock () ; 
		System.out.println (lock.getHoldCount ()); 
		doSomething (); // needs to be locked portion 
		lock.unlock (); 
		System.out.println (lock.getHoldCount ()); 
 } 
	
 public void doSomething ( ) throws InterruptedException { 
	 Lock.lock (); 
	 System.out.println (lock.getHoldCount ()); 
	 //. . . . . . 
	 lock.unlock (); 
	 System.out.println (lock.getHoldCount ()); 
 }
 
	static void main public (String [] args) {throws InterruptedException 
		LockTest03 = new new LockTest03 Test (); 
		test.a (); 
	} 
 
} 
// reentrant lock 
class ReLock { 
	if occupied // 
	Private isLocked = Boolean to false; 
	/ / thread variable storage 
	Private the thread lockedBy = null; 
	// counter locks: locks use frequency and 
	Private holdCount int = 0; 
	// a lock 
	public void the synchronized lock () throws InterruptedException { 
		the thread Thread.currentThread = T (); 
		the while (isLocked ! && lockedBy = T) { 
			the wait (); 
		} 
		
		isLocked = to true; 
		lockedBy = T; 
		holdCount ++; 
	} 
	// release lock 
	public synchronized void unlock () {
		if(Thread.currentThread() == lockedBy) {
			holdCount --;
			if(holdCount == 0) {
				isLocked = false;
				notify();
				lockedBy = null;
			}
		}
	}
	public int getHoldCount() {
		return holdCount;
	}
}

  

If you need a new ReentrantLock just on the line:

ReentrantLock relock = new ReentrantLock();
relock.lock();//加锁
relock.unlock();//解锁

  

 

Guess you like

Origin www.cnblogs.com/Scorpicat/p/12012539.html
Recommended