Fair lock ： It means that multiple threads acquire locks according to the order in which they apply for locks . It's like queuing up to buy food , first come , first served , First come, first served , It's fair , That's the queue
Not fair lock ： The order in which multiple threads acquire locks , It's not in the order of applying for locks . It is possible that the thread that applied first gets the lock before the thread that applied first , In a highly concurrent environment , It may cause priority reversal , Or hungry threads （ That is, a thread can't wait for the lock ）
ReentrantLock The creation of can specify the boolean Type to get fair lock or unfair lock , Default is unfair lock
Lock lock = new ReentrantLock(true); /* Create a reentrant lock .true Fair lock ,false It means unfair lock . The default is false. */
Fair lock ： In a concurrent environment , Each thread will first check the waiting queue maintained by the lock when acquiring the lock , If it is empty , Or wait for the first one in the queue . Take the lock , Otherwise it will join the waiting queue , In the future according to FIFO The rules of get themselves from the queue .
Not fair lock ： Unfair locks are rude , Come up and try to own the lock , If the attempt fails , We'll use a fair lock .
The advantage of unfair lock is that throughput is larger than fair lock , about
synchronized for , It's also a kind of unfair lock .