Java thread fair lock ReentrantLock (boolean fair), reentrantlock fair lock
I. Fair lock
1. Why is there a fair lock?
The CPU selects a thread randomly while waiting for the queue to schedule the thread. Because of this randomness, the thread cannot be guaranteed first-come-first-served (the lock controlled by synchronized is such an unfair lock ). However, this will result in hunger, that is, some threads (lower-priority threads) may never be able to obtain the execution right of the cpu, and high-priority threads will constantly force its resources. So how can we solve hunger? This requires a fair lock.
Another cause of hunger is that a thread occupies resources and does not release the resources. Other threads that need the resources can only be in the infinite waiting state. Here we mainly solve the first hunger problem.
2. What is a fair lock?
The fair lock ensures that threads are executed in chronological order to avoid hunger. However, fair locks are more efficient because an ordered queue needs to be maintained for sequential execution.
Ii. Fair lock
JDK1.5 provides us with an internship fair lock method. The constructor for creating fair locks is:
Java. util. concurrent. locks. ReentrantLock
public ReentrantLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); }
Judge the value of fair to determine whether the ReentrantLock uses the fair lock FairSync or the unfair lock NonfairSync.
Fair lock Demo
Package com. jalja. base. threadTest; import java. util. concurrent. locks. reentrantLock; public class LockFairTest implements Runnable {// create a fair lock private static ReentrantLock lock = new ReentrantLock (true); public void run () {while (true) {lock. lock (); try {System. out. println (Thread. currentThread (). getName () + "get lock");} finally {lock. unlock () ;}} public static void main (String [] args) {LockFairTest lft = new LockFairTest (); Thread th1 = new Thread (lft ); thread Th1 = new Thread (lft); th1.start (); th2.start ();}}
Execution result:
Thread-1 get lock Thread-0 get lock Thread-1 get lock Thread-0 get lock Thread-1 get lock Thread-0 get lock Thread-1 get lock Thread-0 get lock thread-1 get lock Thread-0 get lock Thread-1 get lock Thread-0 get lock Thread-1 get lock Thread-0 get lock Thread-1 get lock Thread-0 get lock
This is part of the execution result. The analysis result shows that the two threads are executed alternately, and almost no one thread is executed multiple times in a row.