如何建设一个网站站,网站的模板怎么做,电子及商务网站建设报告,做网站坚持原创文章有什么好处目录 一、是什么#xff1f;二、简单使用三、semaphore应用四、Semaphore原理 一、是什么#xff1f;
Semaphore#xff1a;信号量#xff0c;用来限制能同时访问共享资源的线程上限
二、简单使用
public class TestSemaphore {public static void main(String[] args) … 目录 一、是什么二、简单使用三、semaphore应用四、Semaphore原理 一、是什么
Semaphore信号量用来限制能同时访问共享资源的线程上限
二、简单使用
public class TestSemaphore {public static void main(String[] args) {// 1. 创建 semaphore 对象Semaphore semaphore new Semaphore(3);// 2. 10个线程同时运行for (int i 0; i 10; i) {new Thread(() - {try {semaphore.acquire();} catch (InterruptedException e) {e.printStackTrace();}try {log.debug(running...);sleep(1);log.debug(end...);} finally {semaphore.release();}}).start();}}
}结果始终只有三个线程处于正在运行的状态 三、semaphore应用
使用semaphore限流在访问高峰期时让请求线程阻塞。当然它只适合限制单机线程数量并且是仅限制线程数而不是限制资源数例如连接数使用Semaphore实现简单连接池对比享元模式下的实现用wait和notify性能和可读性要更好
class Pool {// 1. 连接池大小private final int poolSize;// 2. 连接对象数组private Connection[] connections;// 3. 连接状态数组 0 表示空闲 1 表示繁忙private AtomicIntegerArray states;private Semaphore semaphore;// 4. 构造方法初始化public Pool(int poolSize) {this.poolSize poolSize;// 让许可数与资源数一致this.semaphore new Semaphore(poolSize);this.connections new Connection[poolSize];this.states new AtomicIntegerArray(new int[poolSize]);for (int i 0; i poolSize; i) {connections[i] new MockConnection(连接 (i1));}}// 5. 借连接public Connection borrow() {// t1, t2, t3// 获取许可try {semaphore.acquire(); // 没有许可的线程在此等待} catch (InterruptedException e) {e.printStackTrace();}for (int i 0; i poolSize; i) {// 获取空闲连接if(states.get(i) 0) {if (states.compareAndSet(i, 0, 1)) {log.debug(borrow {}, connections[i]);return connections[i];}}}// 不会执行到这里return null;}// 6. 归还连接public void free(Connection conn) {for (int i 0; i poolSize; i) {if (connections[i] conn) {states.set(i, 0);log.debug(free {}, conn);semaphore.release();break;}}}
}四、Semaphore原理