《Java 并发编程》ReentrantLock详细分析
前言
原理
ReentrantLock案例
import java.util.concurrent.locks.ReentrantLock; public class ReentrantLockDemo { public static int k = 0; public static ReentrantLock reentrantLock = new ReentrantLock(); public static void main(String[] args) { ReentrantLock reentrantLock = new ReentrantLock(); Thread thread = new Thread(()->{ reentrantLock.lock(); // 加锁 try { for (int i = 0; i < 100; i++) { k++; } System.out.println("k="+k); } catch (Exception e) { e.printStackTrace(); } finally { reentrantLock.unlock(); // 显示锁,解锁必须放入finally中执行。 } }); thread.start(); } }
运行结果:
源码:
public ReentrantLock() { sync = new NonfairSync(); }
默认创建的是非公平锁。
public ReentrantLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); }
通过创建对象不同来创建非公平锁。
公平非公平,原理很简单,公平老老实实加入队列,非公平先试试能不能加锁,不能才加入队列。
This moment will nap, you will have a dream; But this moment study,you will interpret a dream.