手写Semaphore信号量
public class MySemaphore { private Sync sync; public MySemaphore(int count) { sync = new Sync(count); } public void acquire() { sync.acquireShared(1); } public void release() { sync.releaseShared(1); } class Sync extends AbstractQueuedSynchronizer { public Sync(int count) { setState(count); } @Override protected int tryAcquireShared(int arg) { for (; ; ) { int oldState = getState(); int newState = oldState - arg; if (compareAndSetState(oldState, newState)) { return newState < 0 ? -1 : 1; } } } @Override protected boolean tryReleaseShared(int arg) { // true false什么时候返回true和false newState>0 true <0 for (; ; ) { int oldState = getState(); //+1 int newState = oldState + arg; if (newState < oldState) { throw new Error("Maximum permit count exceeded"); } if (compareAndSetState(oldState, newState)) { //这里这两种写法都一样 return true; //return newState>0; } } } } public static void main(String[] args) { // 设置aqs状态为3 只能限制有3线程执行代码 限流 做多可以容量3个人 MySemaphore semaphore = new MySemaphore(3); for (int i = 1; i <= 10; i++) { new Thread(() -> { // aqs状态会减去1 如果状态=0的情况下 semaphore.acquire(); System.out.println(Thread.currentThread().getName() + ",进入成功"); // aqs 状态+1 同时唤醒aqs正在阻塞的线程 semaphore.release(); }).start(); } } }
早年同窗始相知,三载瞬逝情却萌。年少不知愁滋味,犹读红豆生南国。别离方知相思苦,心田红豆根以生。