信号量实例
来源:互联网 发布:网络加油站网站 编辑:程序博客网 时间:2024/05/01 23:13
package cn.hc.sort.thread;import java.util.ArrayList;import java.util.List;import java.util.concurrent.BlockingQueue;import java.util.concurrent.Semaphore;/** * 信号量实例 * Created by yhc on 2015/5/5. */public class SemaphoreTest { private static class Connection { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } } private static class Pool { private List<Connection> idlePool = new ArrayList<Connection>(32); private List<Connection> usedPool = new ArrayList<Connection>(32); private Semaphore semaphore=new Semaphore(32); public void init() { //初始化连接 System.out.println("初始化连接池..."); for (int i = 0; i < 32; i++) { Connection connection=new Connection(); connection.setId(i); idlePool.add(connection); } } /**** * 初始化连接 * @return */ public Connection get(){ try{ System.out.println("获取连接对象,连接数量:"+semaphore.availablePermits()); semaphore.acquire(); Connection connection= idlePool.remove(0); usedPool.add(connection); System.out.println("获取连接,id="+connection.getId()); return connection; }catch(Exception e){ e.printStackTrace(); } return null; } /** * 释放连接 * @param connection */ public void release(Connection connection){ try{ System.out.println("释放连接,可用连接数:"+semaphore.availablePermits()); usedPool.remove(connection); idlePool.add(connection); System.out.println("释放连接,id="+connection.getId()); }catch (Exception e){ e.printStackTrace(); }finally { semaphore.release(); } } } public static void main(String[] args) { SemaphoreTest semaphoreTest=new SemaphoreTest(); final Pool pool=new SemaphoreTest.Pool(); pool.init(); for (int i = 0; i < 100; i++) { Thread thread=new Thread(new Runnable() { @Override public void run() { Connection connection = pool.get(); //TODO 复杂的操作,加载数据... try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }finally { //释放连接 pool.release(connection); } } }); thread.start(); } System.out.println("End"); }}
0 0
- 信号量实例
- 信号量实例
- Linux信号量编程实例
- linux 信号量使用实例
- 信号量使用实例
- Linux信号量编程实例
- 共享内存+信号量 实例
- Linux信号量编程实例
- Linux信号量编程实例
- Posix信号量实例
- C++多线程实例-信号量
- 共享内存+信号量 实例
- UCOSII 信号量和信号量集实例
- Linux信号量semaphore编程实例
- Linux_信号量使用实例详解
- 【Linux基础】信号量应用实例
- 3-2信号量驱动实例
- 信号量的PV操作实例
- shell $含义
- 四、配置提示
- 探究java初始化的过程
- Linux常用命令大全
- 驱动程序和应用程序之间的体系结构不匹配
- 信号量实例
- Android工具/网址
- 避免UITableView滚动时有重影
- 素数与哥德巴赫猜想
- 两个字符串是变位词
- 希尔排序
- 【记录帖】Mac下的Vim的配置
- Failed while installing Dynamic Web Module 3.0
- Ruby元编程笔记<二>