java concurrent - semaphore(许可集)的作用

来源:互联网 发布:淘宝售后客服招聘 编辑:程序博客网 时间:2024/05/16 00:52

semaphore 作为一个计数信号量,也可认为是一个许可集,通过许可的获取(acquire)和释放(release)来控制访问内容的线程数量;

当设置信号量为1时,可以作为一个琐来使用;


/** * 模拟乘客车站排队买票(不是使用排队的模式,而是使用争抢买票的模式) * */public class SemaphoreUtil implements Runnable{/*当前为第几人*/private int nowPNum;/*管理人员*/private Semaphore semaphore;public SemaphoreUtil(int nowPNum, Semaphore semaphore){this.nowPNum = nowPNum;this.semaphore = semaphore;}public void run(){/*查看是否有空闲窗口*/if(semaphore.availablePermits() > 0){System.out.println("当前买票人为第" + nowPNum + "人,有空闲窗口");}else{System.out.println("当前买票人为第" + nowPNum + "人,无空闲窗口");}try {/*颁发一个许可*/semaphore.acquire();System.out.println("第" + nowPNum + "人开始买票");Thread.sleep(5*1000);System.out.println("第" + nowPNum + "人买票结束");/*释放许可*/semaphore.release();} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args){ExecutorService excetor = Executors.newCachedThreadPool();Semaphore semaphore = new Semaphore(2);for(int i = 0;i < 10;i++){SemaphoreUtil s = new SemaphoreUtil((i + 1), semaphore);excetor.execute(s);}excetor.shutdown();}}

semaphore一般可以使用在排队购票、排队上车等多人员访问少数资源的场景中

0 0