AbstractQueuedSynchronizer(AQS)实现排它锁、重入锁、共享锁、公平锁

为了方便写到一起了,有些代码需要简单整理:

public class MyAQSLock extends AbstractQueuedSynchronizer {
    private static final MyAQSLock MY_AQS_LOCK = new MyAQSLock();
    private static final AtomicInteger SHARE_LOCK = new AtomicInteger(10);

    public static void main(String[] args) throws InterruptedException {
        //排它锁
        testExclusiveLock();
        //重入锁
        testReentryLock();
        //共享锁
        testSharedLock(10);
        //公平锁
        testFairLock();
    }

    public static void testExclusiveLock() {
        MY_AQS_LOCK.setState(0);
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                MY_AQS_LOCK.tryAcquire(1);
                MY_AQS_LOCK.tryRelease(1);
            }).start();
        }
    }

    public static void testReentryLock() {
        MY_AQS_LOCK.tryAcquire(1);
        MY_AQS_LOCK.tryAcquire(1);
        MY_AQS_LOCK.tryRelease(1);
        MY_AQS_LOCK.tryRelease(1);
        System.out.println(MY_AQS_LOCK.getState());
    }

    public static void testFairLock() {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                MY_AQS_LOCK.tryAcquire(1);
                MY_AQS_LOCK.tryRelease(1);
            }).start();
        }
        System.out.println(MY_AQS_LOCK.getState());
    }

    public static void testSharedLock(int count) throws InterruptedException {
        MY_AQS_LOCK.setState(count);
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                MY_AQS_LOCK.tryAcquireShared(1);
                MY_AQS_LOCK.tryReleaseShared(1);
            }).start();
        }
        Thread.sleep(1000);
        System.out.println("剩余锁:" + MY_AQS_LOCK.getState());
    }


    /**
     * 是否拥有锁
     */
    protected boolean isHeldExclusively() {
        return getState() > 0;
    }

    /**
     * 获取锁,重试机制需要重写
     * hasQueuedPredecessors 判断队列中是否有前驱节点
     * Thread.currentThread().equals(getExclusiveOwnerThread()) 判断当前线程是否已经持有锁
     */
    public boolean tryAcquire(int acquires) {
        if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) {
            System.out.println("公平锁");
            return true;
        }
        if (Thread.currentThread().equals(getExclusiveOwnerThread())) {
            System.out.println("重入锁");
            setState(getState() + acquires);
            return true;
        }
        compareAndSetState(0, acquires);
        System.out.println("获取到锁");
        setExclusiveOwnerThread(Thread.currentThread());
        return true;
    }

    /**
     * 释放锁
     */
    protected boolean tryRelease(int releases) {
        setExclusiveOwnerThread(null);
        System.out.println("释放锁");
        setState(getState() - releases);
        return true;
    }

    @Override
    protected int tryAcquireShared(int arg) {
        while (true) {
            int state = getState();
            if (state > 0 && compareAndSetState(state, state - arg)) {
                System.out.println("获取到锁:" + SHARE_LOCK.decrementAndGet());
                return getState();
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected boolean tryReleaseShared(int arg) {
        int i = SHARE_LOCK.incrementAndGet();
        setState(i);
        System.out.println("释放锁:" + i);
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值