Semaphore

74 阅读1分钟

用法

public static void main(String[] args)  {
        // 相当于创建一个最多两把锁的对象
        Semaphore semaphore = new Semaphore(2);

        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 取到一把锁,只有取到的时候才能继续往下执行
                        // 可以传参数,传几就是拿到几把锁
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() + "start");
                        Thread.sleep(200);
                        System.out.println(Thread.currentThread().getName() + "end");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        // 放回去一把
                        // 也可以传参数,需要和拿到的数量一样
                        semaphore.release();
                    }

                }
            }, "Thread" + i).start();
        }
}

作用

限流