前言
原理
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(); }
通過創建對象不同來創建非公平鎖。
公平非公平,原理很簡單,公平老老實實加入隊列,非公平先試試能不能加鎖,不能才加入隊列。