java自定义lock锁

45 篇文章 0 订阅
37 篇文章 0 订阅
实现原理

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");
    }

在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ITzhongzi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值