- 单机锁代码
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;public class AloneLock implements Lock {AtomicReference<Thread> owner = new AtomicReference<>();LinkedBlockingQueue<Thread> waiters = new LinkedBlockingQueue<>();@Overridepublic void lock() {while (!owner.compareAndSet(null,Thread.currentThread())){waiters.add(Thread.currentThread());LockSupport.park();waiters.remove(Thread.currentThread());}}@Overridepublic void unlock() {if(owner.compareAndSet(Thread.currentThread(),null)){for (Object object:waiters.toArray()){Thread next= (Thread) object;LockSupport.unpark(next);}}}@Overridepublic void lockInterruptibly() throws InterruptedException {}@Overridepublic boolean tryLock() {return false;}@Overridepublic boolean tryLock(long time, TimeUnit unit) throws InterruptedException {return false;}@Overridepublic Condition newCondition() {return null;}
}
- 分布式锁