实现原理
Java Lock底层是用 AQS + Cas + LockSupport实现的。
- 思路
- 使用原子类 AtomicInteger 定义锁的状态
- 当一个线程修改状态之后,其他线程都处于等待状态
- 当线程释放锁之后,其他线程被唤醒,重新竞争锁资源
核心代码
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;
public class CustomLock {
// 0 上锁 1 释放锁
private AtomicInteger lockState = new AtomicInteger(0);
// 当前获得锁的线程
private Thread getLockThread = null;
// 阻塞线程队列
private ConcurrentLinkedDeque<Thread> threadList = new ConcurrentLinkedDeque();
public void lock(){
acquire();
}
public boolean acquire(){
for(;;) {
if(compareAndSet(0, 1)) {
// 获取锁成功
getLockThread = Thread.currentThread();
return true;
}
// 获取锁失败
Thread thread = Thread.currentThread();
threadList.add(thread);
LockSupport.park();
}
}
public boolean compareAndSet(int expect, int update){
return lockState.compareAndSet(expect, update);
}
public boolean unLock(){
if(getLockThread == null) {
return false;
}
if(Thread.currentThread() == getLockThread) {
boolean result = compareAndSet(1, 0);
if(result) {
// 公平锁唤醒
Thread first = threadList.getFirst();
LockSupport.unpark(first);
// 非公平锁
// 非公平锁的唤醒需要 使用循环把列表中的所有的 线程全部唤醒
}
return true;
}
return false;
}
}
测试demo
public static void main(String[] args) throws InterruptedException {
CustomLock customLock = new CustomLock();
customLock.lock();
new Thread(() -> {
System.out.println("start");
customLock.lock();
System.out.println("end");
}).start();
Thread.sleep(1000);
customLock.unLock();
System.out.println("hhh");
}