Semaphore


 

Semaphore 信号量,用来控制同一时间源可被访问线程数量,一般可用于流量的控制。其内部是基于AQS的共享模式,AQS的状表示的数量,在数量不够时线程将会被挂起;而一旦有一个线放一个源,那就有可能重新醒等待列中的线继续执行。

 

造方法

 

    public Semaphore(int permits) {

        sync = new NonfairSync(permits);

    }

 

    public Semaphore(int permits, boolean fair) {

        sync = fair ? new FairSync(permits) : new NonfairSync(permits);

    }

 

使用示例

 

public class SemaphoreTest {

    static class Parking {

        //信号量

        private Semaphore semaphore;

 

        Parking(int count) {

            semaphore = new Semaphore(count);

        }

 

        public void park() {

            try {

                //取信号量

                semaphore.acquire();

                long time = (long) (Math.random() * 10000);

                System.out.println(Thread.currentThread().getName() + "入停车场,停" + time + "秒...");

                Thread.sleep(time);

                System.out.println(Thread.currentThread().getName() + "出停车场...");

            } catch (InterruptedException e) {

                e.printStackTrace();

            } finally {

                semaphore.release();

            }

        }

    }

 

    static class Car extends Thread {

        Parking parking;

 

        Car(Parking parking) {

            this.parking = parking;

        }

 

        @Override

        public void run() {

            parking.park();     //入停车场

        }

    }

 

    public static void main(String[] args) {

        Parking parking = new Parking(3);

        for (int i = 0; i < 5; i++) {

            new Car(parking).start();

        }

    }

}

Thread-0入停车场,停8243秒...

Thread-2入停车场,停7086秒...

Thread-4入停车场,停696秒...

Thread-4出停车场...

Thread-3入停车场,停1007秒...

Thread-3出停车场...

Thread-1入停车场,停1972秒...

Thread-1出停车场...

Thread-2出停车场...

Thread-0出停车场...