Java Semaphore用法
操作系统的信号量是个很重要的概念,在进程控制方面都有应用。Java 并发库 的Semaphore 可以很轻松完成信号量控制,Semaphore可以控制某个资源可被同时访问的个数,acquire()获取一个许可,如果没有就等待,而release()释放一个许可。比如在Windows下可以设置共享文件的最大客户端访问个数。
Semaphore维护了当前访问的个数,提供同步机制,控制同时访问的个数。在数据结构中链表可以保存“无限”的节点,用Semaphore可以实现有限大小的链表。另外重入锁ReentrantLock也可以实现该功能,但实现上要复杂些,代码也要复杂些。
下面是模拟一个连接池,控制同一时间最多只能有50个线程访问。
package com.bijian.study; import java.util.UUID; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class TestSemaphore extends Thread { public static void main(String[] args) { int i = 0; while (i < 500) { i++; new TestSemaphore().start(); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * 控制某资源同时被访问的个数的类 控制同一时间最后只能有50个访问 */ static Semaphore semaphore = new Semaphore(50); static int timeout = 500; public void run() { try { Object connec = getConnection(); System.out.println("获得一个连接" + connec); Thread.sleep(300); releaseConnection(connec); } catch (InterruptedException e) { e.printStackTrace(); } } public void releaseConnection(Object connec) { /* 释放许可 */ semaphore.release(); System.out.println("释放一个连接" + connec); } public Object getConnection() { try {/* 获取许可 */ boolean getAccquire = semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS); if (getAccquire) { return UUID.randomUUID().toString(); } } catch (InterruptedException e) { e.printStackTrace(); } throw new IllegalArgumentException("timeout"); } }
运行结果:
获得一个连接b9914d13-3b01-40fa-9560-f263173bfe25 获得一个连接df3759d8-7f2c-4504-a5c6-f731f3ba07fa 获得一个连接ad4d8f23-45de-43c4-8779-7198f64f34bc 获得一个连接6087180f-4435-4c69-9656-b78bb34a6ff4 获得一个连接6774270e-03a8-4a23-9478-522fe6b458b9 获得一个连接5edaed6e-b949-4e3c-833d-582600702cef 获得一个连接8ef263e5-f157-4a87-ad33-0c3b365bf619 Exception in thread "Thread-50" Exception in thread "Thread-51" Exception in thread "Thread-52" Exception in thread "Thread-53" Exception in thread "Thread-54" Exception in thread "Thread-55" Exception in thread "Thread-56" Exception in thread "Thread-57" Exception in thread "Thread-58" Exception in thread "Thread-59" Exception in thread "Thread-60" Exception in thread "Thread-61" Exception in thread "Thread-62" java.lang.IllegalArgumentException: timeout at com.bijian.study.TestSemaphore.getConnection(TestSemaphore.java:54) at com.bijian.study.TestSemaphore.run(TestSemaphore.java:30) java.lang.IllegalArgumentException: timeout at com.bijian.study.TestSemaphore.getConnection(TestSemaphore.java:54) at com.bijian.study.TestSemaphore.run(TestSemaphore.java:30) java.lang.IllegalArgumentException: timeout
文章来源:http://blog.csdn.net/kevin_luan/article/details/12832523
posted on 2017-06-20 23:08 bijian1013 阅读(666) 评论(0) 收藏 举报
浙公网安备 33010602011771号