One, Fair lock
1. Why there is a fair lock
The CPU is randomly picking a thread in the waiting queue when the thread is dispatched, so it is impossible to guarantee that the thread is first-come first-served (the synchronized-controlled lock is such an unfair lock). However, there is a hunger phenomenon in which some threads (lower priority threads) may never get CPU execution, and high-priority threads constantly enforce their resources. So how to solve the problem of hunger, which requires a fair lock.
Another reason for starvation is that a thread occupies a resource that is not released, and that other threads that need the resource can only be in an infinite wait. Here we mainly solve the first kind of hunger problem.
2, what is the fair lock
A fair lock can ensure that threads are executed in chronological order to avoid starvation. But the efficiency of fair locking is comparatively, because to achieve sequential execution, an ordered queue needs to be maintained.
second, the use of fair lock
JDK1.5 provides us with an internship fair lock method, which creates a fair lock constructor:
Java.util.concurrent.locks.ReentrantLock
Public Reentrantlock (boolean Fair) { newnew nonfairsync (); }
Determine whether a fair lock (Reentrantlock) is using a fair lock fairsync or an unfair lock nonfairsync by judging the value of the check-in.
Fair Lock Demo
Packagecom.jalja.base.threadTest;ImportJava.util.concurrent.locks.ReentrantLock; Public classLockfairtestImplementsrunnable{//Create a fair lock Private StaticReentrantlock lock=NewReentrantlock (true); Public voidrun () { while(true) {lock.lock (); Try{System.out.println (Thread.CurrentThread (). GetName ()+ "Get Lock"); }finally{lock.unlock (); } } } Public Static voidMain (string[] args) {lockfairtest lft=Newlockfairtest (); Thread Th1=NewThread (LFT); Thread Th2=NewThread (LFT); Th1.start (); Th2.start (); }}
Execution Result:
thread-1 Get lock thread-0 Get lock Thread-1 Get lockthread-0 Get lock Thread-1 Get lock thread- 0 Get lock Thread-1 Get lock thread-0 Get lockthread-1 Get lock thread-0 Get lock thread- 1 Get lock thread-0 Get lock Thread-1 Get lockthread-0 Get lock Thread-1 Get lock thread-0 Get lock
This is a partial execution of the interception, and the analysis results show that two threads are executed alternately, with almost no continuous execution of the same thread multiple times.
Java Thread Fair Lock Reentrantlock (Boolean fair)