1. The background
Suppose you have 10 threads. How do you get them to execute sequentially?
Solution: This can be done using multiple threads in conjunction with a “fair lock”. Thread, ReentrantLock
2. Knowledge
Fair lock is to guarantee the order of each thread to obtain the lock under multi-threading, the thread that arrives first gets the lock first, but non-fair lock cannot provide this guarantee.
When a thread tries to acquire a lock, it will first try CAS, and after failure, it will put itself into the lock waiting queue. If the order of multiple locks in the queue is in order, it is a fair lock, and if it is out of order, it is an unfair lock.
The ReentrantLock constructor in Java can default to an unfair lock policy.
ReentrantLock reentrantLock = new ReentrantLock(); // Default "unfair lock" Boolean isFair = true; ReentrantLock reentrantLock2 = new ReentrantLock(isFair); // This constructor produces a "fair lock"Copy the code
Example 3.
The code:
public class Main { static class MyService { ReentrantLock reentrantLock = new ReentrantLock(true); void doSome() { reentrantLock.lock(); System.out.println(string. format("\t\t\t\t thread [%s] execute... , Thread.currentThread().getName())); reentrantLock.unlock(); } } public static void main(String[] args) { final MyService myService = new MyService(); Runnable Runnable = () -> {system.out.println (string.format (" thread [%s] enters...") , Thread.currentThread().getName())); myService.doSome(); }; Thread[] threadArray = new Thread[10]; for (int i = 0; i < 10; i++) { Thread thread = new Thread(runnable); thread.setName("Thread_" + i); threadArray[i] = thread; } Arrays.stream(threadArray).forEach(Thread::start); try { Thread.sleep(20 * 1000); } catch (InterruptedException e) { e.printStackTrace(); }}}Copy the code
Output results:
END