aqs(AbstractQueuedSynchronizer),通过继承此类可以实现自定义aqs,以下为例子:
package com.work.testwork.mylock; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; public class LockTest implements Lock { static class Sync extends AbstractQueuedSynchronizer { @Override protected boolean tryAcquire(int i) { if (!Thread.currentThread().getName().startsWith("my-aqs")) { return false; } Thread var2 = Thread.currentThread(); int var3 = this.getState(); if (var3 == 0) { if (this.compareAndSetState(0, i)) { this.setExclusiveOwnerThread(var2); return true; } } else if (var2 == this.getExclusiveOwnerThread()) { int var4 = var3 + i; if (var4 < 0) { throw new Error("Maximum lock count exceeded"); } this.setState(var4); return true; } return false; } @Override protected boolean tryRelease(int i) { int var2 = this.getState() - i; if (Thread.currentThread() != this.getExclusiveOwnerThread()) { throw new IllegalMonitorStateException(); } else { boolean var3 = false; if (var2 == 0) { var3 = true; this.setExclusiveOwnerThread((Thread) null); } this.setState(var2); return var3; } } Condition getCondition() { return new ConditionObject(); } } Sync sync = new Sync(); @Override public void lock() { sync.acquire(1); } @Override public void lockInterruptibly() throws InterruptedException { sync.acquireInterruptibly(1); } @Override public boolean tryLock() { return sync.tryAcquire(1); } @Override public boolean tryLock(long l, TimeUnit timeUnit) throws InterruptedException { return sync.tryAcquireNanos(1, timeUnit.toNanos(l)); } @Override public void unlock() { sync.release(1); } @Override public Condition newCondition() { return sync.getCondition(); } }
package com.work.testwork; import com.work.testwork.mylock.LockTest; class test_work_application_tests { static LockTest lock = new LockTest(); public static void main(String[] args) { // 线程名称符合 Thread thread1 = new Thread(test_work_application_tests::testLock);// 开启线程 thread1.setName("my-aqssdsd2"); thread1.start(); // 线程名称不符合 Thread thread2 = new Thread(test_work_application_tests::testLock);// 开启线程 thread2.setName("one"); thread2.start(); } private static void testLock() { lock.lock(); //重写方法 try { System.out.println("我获取到了锁" + Thread.currentThread().getName()); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }
标签:return,aqs,Thread,lock,sync,Override,public,自定义 From: https://www.cnblogs.com/goPush/p/17158701.html