利用AQS实现一个协作类-AQS开门
利用AQS实现一个协作类-AQS开门的实例代码如下所示:
package com.yang.aqs; import java.util.concurrent.locks.AbstractQueuedSynchronizer; /** * 我们模拟一个门,一个线程去开门,剩余的线程去等待开门 */ public class MyLatch { private final Sync sync = new Sync(); /** * 等待开门 */ public void await() { sync.tryAcquire(0); } /** * 开门 把state设置为1 */ public void signal() { sync.tryRelease(0); } private class Sync extends AbstractQueuedSynchronizer { @Override protected int tryAcquireShared(int arg) { //如果小于0就要排队 return (getState() == 1) ? 1 : -1; } @Override protected boolean tryReleaseShared(int arg) { setState(1); return true; } @Override protected boolean tryAcquire(int arg) { return (getState() == 1) ? true : false; } @Override protected boolean tryRelease(int arg) { setState(1); return true; } } public static void main(String[] args) { MyLatch myLatch = new MyLatch(); for (int i = 0; i < 10; i++) { new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + "尝试去打开门,打开失败,需要等待"); myLatch.await(); System.out.println(Thread.currentThread().getName() + "门开了,可以进去了"); } }).start(); } } }