可重入锁意思是object.lock()获取锁后,可以再次使用object.lock()获取锁,如果发生了死锁就不是可重入锁
公平锁就是排队买票,不公平锁就是插队买票
锁实现的基本原理
1.需要一个state变量,标记锁的状态,state至少要有两个值,0,1,对state变量的操作,使用CAS保证线程安全
2.需要记录当前是哪个线程持有锁
3.需要底层支持对一个线程进行阻塞或者唤醒操作
4.需要有一个队列维护所有阻塞的线程,这个队列的要求必须是线程安全的无所队列,需要使用到CAS
有关ReentrantLock实现互斥锁
案例代码
package com.java.test.lock; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * @author yourheart * @Description * @create 2023-01-15 17:31 */ public class ReentrantLockService { private ReentrantLock reentrantLock = new ReentrantLock(); private Condition condition = reentrantLock.newCondition(); private List<String> arrayList = new ArrayList<>(); public void addItems(){ try { reentrantLock.lock(); if (arrayList.size() <= 0) { arrayList.add("买票"); System.out.println("addItems -- > 开始等待删除车票"); condition.await(); } System.out.println("addItems -- > 执行完了"); } catch (Exception e) { } finally { reentrantLock.unlock(); } } public void removeItems() { try { reentrantLock.lock(); if (arrayList.size() >= 0) { arrayList.remove(0); System.out.println("removeItems -- > 车票已删除"); condition.signal(); } System.out.println("removeItems -- > 执行完了"); } catch (Exception e) { } finally { reentrantLock.unlock(); } } }
package com.java.test.lock; import org.junit.Test; /** * @author yourheart * @Description * @create 2023-01-15 17:12 */ public class ReentrantLockTest { @Test public void test() throws InterruptedException { ReentrantLockService lockService=new ReentrantLockService(); new Thread(()->{ lockService.addItems(); }).start(); new Thread(()->{ lockService.removeItems(); }).start(); while (true){ } } }
标签:java,lock,reentrantLock,介绍,互斥,线程,简单,import,public From: https://www.cnblogs.com/q202105271618/p/17035431.html