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
- java concurrent - semaphore(许可集)的作用
- java.util.concurrent.Semaphore
- java.util.concurrent.Semaphore 实例
- java.util.concurrent之Semaphore
- JAVA concurrent包学习--Semaphore
- java.util.concurrent|Semaphore使用
- Java.utils.concurrent包中的几个有用的类(CountDownLatch、CyclicBarrier、Semaphore)
- java.util.concurrent 下的Semaphore CyclicBarrier CountDownLatch 分析使用
- java并发API: Semaphore管理资源许可
- Java多线程工具包java.util.concurrent---Semaphore
- 聊聊高并发(二十五)解析java.util.concurrent各个组件(七) 理解Semaphore
- 同步工具类三:计数信号量(java.util.concurrent.Semaphore)
- Java多线程之concurrent包(四)——Semaphore信号量
- think in java笔记:java.util.concurrent.Semaphore
- concurrent-6-AQS-Semaphore
- concurrent包下的CyclicBarrier和CountDownLatch以及Semaphore
- Java的Semaphore
- Java的信号量Semaphore
- linux版mantis 安装和测试笔记
- Tomcat Servlet Examples threats
- git push 失败
- 三个人去住旅馆,都给老板10元,优惠5元服务员贪污了2元
- Nand flash linux 驱动研究
- java concurrent - semaphore(许可集)的作用
- CentOS下VSFTPD安装配置
- Java中Json对象转成xml字符串
- TQ2440内核配置和编译及相关测试方法,(很全)
- Android中添加USB键盘的CapsLock键
- 表单验证
- ffmpeg源码分析二:main函数和transcode函数
- cocos2d-x3.0 RichText
- windows句柄---转载自百度百科