Semaphore
来源:互联网 发布:购买淘宝小号安全吗 编辑:程序博客网 时间:2024/05/30 23:00
Semaphore
Semaphore是一个线程同步的辅助类,可以维护当前访问自身的线程个数。使用Semaphore可以控制同时访问资源的线程个数,例如,实现一个文件允许的并发访问数。
相关方法:
void acquire(): 从此信号量获取一个许可,在提供一个许可前一直将线程阻塞,否则线程被中断。
void release(): 释放一个许可,将其返回给信号量。
int availablePermits():返回此信号量中当前可用的许可数。
boolean hasQueuedThreads():查询是否有线程正在等待获取。
代码
下面是一个同时只能有最多5个线程访问的例子。
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;public class SemaphoreTest { public static void main(String[] args) { // 线程池 ExecutorService exec = Executors.newCachedThreadPool(); // 只能5个线程同时访问 final Semaphore semp = new Semaphore(5); // 模拟10个客户端访问 for (int index = 0; index < 10; index++) { final int NO = index; Runnable run = new Runnable() { public void run() { try { // 获取许可 semp.acquire(); System.out.println("Accessing: " + NO); Thread.sleep((long) (Math.random() * 6000)); // 访问完后,释放 semp.release(); // availablePermits()指的是当前信号灯库中有多少个可以被使用 System.out.println("----------available count: " + semp.availablePermits()); } catch (InterruptedException e) { e.printStackTrace(); } } }; exec.execute(run); } // 退出线程池 exec.shutdown(); }}
运行结果
Accessing: 0Accessing: 1Accessing: 2Accessing: 3Accessing: 4-----------------available count: 1Accessing: 5-----------------available count: 1Accessing: 7-----------------available count: 1Accessing: 9-----------------available count: 1Accessing: 6-----------------available count: 1Accessing: 8-----------------available count: 1-----------------available count: 2-----------------available count: 3-----------------available count: 4-----------------available count: 5
0 0
- Semaphore
- semaphore
- semaphore
- Semaphore
- Semaphore
- semaphore
- Semaphore
- semaphore
- Semaphore
- Semaphore
- Semaphore
- semaphore
- Semaphore
- Semaphore
- semaphore
- Semaphore
- semaphore
- Semaphore
- 在本地将spark作业运行到远程集群
- 读写Android系统联系人
- OpenGL---二维光线追踪
- 2.分布式锁
- 修改Tomcat默认访问页面
- Semaphore
- LeetCode : Move Zeroes
- 并发学习2-使用Thread类来驱动实现Runnable接口的类
- 我眼中的光明·第六周·莲池·三
- 多线程异常处理
- 啊是大
- makefile 中支持这四个命令:make,make install ,make clean和make uninstall
- 为eclipse配置python环境
- HDU_4282