Semaphore
来源:互联网 发布:itunes软件下载目录 编辑:程序博客网 时间:2024/05/16 10:21
public class SemaphoreThread {public static void main(String[] args) {ExecutorService service = Executors.newCachedThreadPool();final Semaphore sp = new Semaphore(3);for(int i=0;i<10;i++){Runnable runnable = new Runnable(){public void run(){try {sp.acquire();} catch (InterruptedException e1) {e1.printStackTrace();}System.out.println("线程" + Thread.currentThread().getName() + "进入,当前已有" + (3-sp.availablePermits()) + "个并发");try {Thread.sleep((long)(Math.random()*10000));} catch (InterruptedException e) {e.printStackTrace();}System.out.println("线程" + Thread.currentThread().getName() + "即将离开");sp.release();//下面代码有时候执行不准确,因为其没有和上面的代码合成原子单元System.out.println("线程" + Thread.currentThread().getName() + "已离开,当前已有" + (3-sp.availablePermits()) + "个并发");}};service.execute(runnable);}}}
一个计数信号量。从概念上讲,信号量维护了一个许可集。如有必要,在许可可用前会阻塞每一个 acquire()
,然后再获取该许可。每个release()
添加一个许可,从而可能释放一个正在阻塞的获取者。但是,不使用实际的许可对象,Semaphore
只对可用许可的号码进行计数,并采取相应的行动。
0 0
- Semaphore
- semaphore
- semaphore
- Semaphore
- Semaphore
- semaphore
- Semaphore
- semaphore
- Semaphore
- Semaphore
- Semaphore
- semaphore
- Semaphore
- Semaphore
- semaphore
- Semaphore
- semaphore
- Semaphore
- 初探BP神经网络工具箱
- Maven新建SpringMVC项目
- web.xml项目实例
- @SessionAttributes的覆盖与添加
- OpenCV仿射变换+投射变换+单应性矩阵
- Semaphore
- 【状压DP】[UVA1252] Twenty Questions
- 关于keystore
- MXS - CSDN 博客开写啦!
- 第16周项目2-比较两个字符串长度(指针作形参)
- iOS Crash闪退信息捕获工具类
- jqueryeasyui-datagrid-编辑器扩展-日期时间编辑器
- android4.0电源管理详解
- Qt SVG Viewer Demo 解读