为了方便写到一起了,有些代码需要简单整理: 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; } }
AbstractQueuedSynchronizer(AQS)实现排它锁、重入锁、共享锁、公平锁
最新推荐文章于 2023-09-23 22:19:20 发布