java模板模式与AQS实现( 五 )

< 0) {return newCount; //分配失败,返回负数,详见AQS注释}if (compareAndSetState(cur, newCount)) {return newCount; //分配成功}}}@Overrideprotected boolean tryReleaseShared(long arg) {while (true) {long cur = getState();long newCount = cur + arg;if (compareAndSetState(cur, newCount)) {return true;}}}}/*** Lock接口方法*/@Overridepublic void lock() {sync.acquireShared(1L);}@Overridepublic void lockInterruptibly() throws InterruptedException {}@Overridepublic boolean tryLock() {return false;}@Overridepublic boolean tryLock(long time, TimeUnit unit) throws InterruptedException {return false;}@Overridepublic void unlock() {sync.releaseShared(1L);}@Overridepublic Condition newCondition() {return null;}}
调用:设置5个资源,8个线程共享这5个资源 。
NSourceLock nSourceLock = new NSourceLock(5);for (int i = 0; i < 8; i++) {new Thread(() -> {nSourceLock.lock();try {System.out.println(Thread.currentThread().getName() + " lock " + System.currentTimeMillis());Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} finally {System.out.println(Thread.currentThread().getName() + " unlock " + System.currentTimeMillis());nSourceLock.unlock();}}, "th" + i).start();}
输出:
输出可看出,首先是0~4号线程获取到资源,大约一秒后0号释放一个资源,5号得以获取一个资源;随后2号释放一个,6号获取一个;随后3号释放一个,7号获取一个;随后相继释放资源 。