package com.test4;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* 信号量
*
* @author 林计钦
* @version 1.0 2013-7-25 下午02:03:40
*/
public class SemaphoreTest {
public static void main(String[] args) {
// 线程池
ExecutorService exec = Executors.newCachedThreadPool();
// 只能5个线程同时访问
final Semaphore semp = new Semaphore(5);
// 模拟20个客户端访问
for (int index = 1; index <= 20; 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() * 10000));
// 访问完后,释放
semp.release();
//availablePermits()指的是当前信号灯库中有多少个可以被使用
System.out.println("getQueueLength:"+semp.getQueueLength()+"------------availablePermits:" + semp.availablePermits()+"--------drainPermits:"+semp.drainPermits());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
exec.execute(run);
}
// 退出线程池
exec.shutdown();
}
}
运行结果:
Accessing: 1
Accessing: 2
Accessing: 3
Accessing: 4
Accessing: 5
Accessing: 6
getQueueLength:14------------availablePermits:0--------drainPermits:0
Accessing: 7
getQueueLength:13------------availablePermits:0--------drainPermits:0
getQueueLength:13------------availablePermits:0--------drainPermits:0
Accessing: 10
Accessing: 11
getQueueLength:11------------availablePermits:0--------drainPermits:0
Accessing: 8
getQueueLength:10------------availablePermits:0--------drainPermits:0
Accessing: 12
getQueueLength:9------------availablePermits:0--------drainPermits:0
getQueueLength:9------------availablePermits:0--------drainPermits:0
Accessing: 13
getQueueLength:8------------availablePermits:0--------drainPermits:0
Accessing: 9
getQueueLength:7------------availablePermits:0--------drainPermits:0
Accessing: 14
Accessing: 15
getQueueLength:5------------availablePermits:0--------drainPermits:0
getQueueLength:5------------availablePermits:1--------drainPermits:1
Accessing: 16
getQueueLength:4------------availablePermits:0--------drainPermits:0
getQueueLength:4------------availablePermits:0--------drainPermits:0
Accessing: 17
Accessing: 18
getQueueLength:2------------availablePermits:0--------drainPermits:0
getQueueLength:2------------availablePermits:0--------drainPermits:0
Accessing: 19
Accessing: 20
getQueueLength:0------------availablePermits:0--------drainPermits:0
getQueueLength:0------------availablePermits:1--------drainPermits:1
getQueueLength:0------------availablePermits:1--------drainPermits:1
getQueueLength:0------------availablePermits:1--------drainPermits:1
getQueueLength:0------------availablePermits:1--------drainPermits:1