java:通过Semaphore构建对象池
来源:互联网 发布:足球关注分析软件 编辑:程序博客网 时间:2024/05/01 17:43
Semaphore
1) 正常的锁(concurrent.locks或synchronized锁)在任何时候都只允许一个任务访问一项资源,而java.util.concurrent.Semaphore计数信号量允许n个任务同时访问该资源,可以把信号量看成是向外分发使用资源的许可证;
2)对象池概念:对象池管理数量有限的对象,当要使用对象时可以签出他们,而在用户使用完毕时,可以将它们签回,这种功能可以封装在一个泛型类中:
class Pool<T>{ private Semaphore avaliable; //管理计数信号量 private List<T> items = new ArrayList<T>(); //管理对象列表 private volatile boolean[] checkOut; //管理对象列表上相应下标的对象的签出情况 private int size; public Pool(Class<T> classObject,int size){ this.size = size; checkOut = new boolean[size]; available = new Semaphore(size); for(int i=0;i<size;i++){ try{ items.add(classObject.newInstance()); }catch(Exception e){ throw new RunTimeException(e); } } } public T checkOut() throw InterruptedException{ //签出对象池的信号量 available.acquire(); return getItem(); } public T getItem(){ for(int i=0;i<size;i++){ if(!checkOut[i]){ checkOut[i] =true; return item.get(i); } } } public void checkIn(T x){ //签入对象池的信号量 if(releaseItem(x)) available.release(); } public boolean releaseItem(T x){ int index = items.indexOf(x); if(index == -1) retrun false; if(checkOut[index]){ checkOut[idnex] = false; return true; } return false; }}//Testclass Demo(){}class CheckOutWorker<T> implements Runnable{ priavte Pool<T> pool; public CheckOutWorker(Pool<T> pool){ this.pool = pool; } public void run(){ try{ T item = pool.checkOut(); <using item to do something> pool.checkIn(item); }catch(Interruptedexception ex){ } } /*or 记录所有已被签出的对象,返回对象列表供主程使用 priavte Pool<T> pool; private List<T> checkOutList = new ArrayList<T>(); public CheckOutWorker(Pool<T> pool){ this.pool = pool;this.checkOutList = checkOutList; } public void run(){ try{ T item = pool.checkOut(); checkOutList.add(item); <using checkOutList to do something> pool.checkIn(item); checkOutList.remove(item); }catch(Interruptedexception ex){ } }*/}class Driver{ void main(){ Pool<Demo> pool = new Pool(Demo.class,N); ExecutorService exec = Executors.newChacedTheadPool(); for(int i=0;i<N;i++) exec.execute(new CheckOut(pool)); exec.shoudown(); }}
0 0
- java:通过Semaphore构建对象池
- Java Semaphore
- java Semaphore
- Java Semaphore
- java Semaphore
- java semaphore
- java Semaphore
- java-Semaphore
- Java Semaphore
- Semaphore Java
- GDI+ Image通过资源ID构建对象
- GDI+ Image通过资源ID构建对象
- java 对象树的构建
- 通过maven构建一个java项目
- 通过maven构建一个java项目
- 【JAVA学习】4.Java对象构建理解
- java信号量Semaphore
- Java Semaphore用法
- memcahce使用
- 面向对象—工厂模式示例(数据库示例)
- linux SSH无密码登录设置 仍需输密码
- 返回指定的 的界面控制器
- 找到一个LINUX与WINDOWS实现实时文本通信的办法
- java:通过Semaphore构建对象池
- macos阻止硬盘休眠
- iOS 调取本地地图以及三方地图
- win32之简易记事本
- 玩转Google开源C++单元测试框架Google Test系列(gtest)之六 - 运行参数
- AndroidShortcuts
- distinct和group by的效率
- 一个c++转c的工具(cfront源码)
- 解决VS2015无ReportViewer和Rdlc的问题