package com.demo.work.test; 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 LockTest lock = new LockTest(); public static void test1(String[] args) { // 线程名称符合 Thread thread1 = new Thread(LockTest::testLock);// 开启线程 thread1.setName("my-aqssdsd2"); thread1.start(); // 线程名称不符合 Thread thread2 = new Thread(LockTest::testLock);// 开启线程 thread2.setName("one"); thread2.start(); } public static void testLock() { lock.lock(); //重写方法 try { System.out.println("我获取到了锁" + Thread.currentThread().getName()); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } 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(); } }
以上,通过aqs类中的模板,我们可以快速定义自己的锁。如上,我需要自定义非公平锁,只需要重写tryAcquire和tryRelease方法即可,其他可以直接调用aqs内实现方法,如需自定义其他可以根据需求自行修改
标签:return,AQS,Thread,sync,Override,new,public,自定义 From: https://www.cnblogs.com/goPush/p/17214681.html