手写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();

        }
    }


}

 

posted @ 2024-07-25 14:05  山河永慕~  阅读(4)  评论(0编辑  收藏  举报