package thread.semaphore;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class Test {
/**
* @author jzh 2011-12-27
* @param args
*/
public static void main(String[] args) {
// 创建一个线程池(创建一个可根据需要创建新线程的线程池)
// Executors 类提供了用于此包中所提供的执行程序服务的工厂方法
ExecutorService pool = Executors.newCachedThreadPool();
// 设置许可数(5个柜台)
final Semaphore semaphore = new Semaphore(5);
// 设置客户端数量(10个顾客)
for (int i = 1; i <= 10; i++) {
final int code = i;
Runnable run = new Runnable() {
public void run() {
try {
// 从此信号量获取一个许可,在提供一个许可前一直将线程阻塞,否则线程被中断。
semaphore.acquire();
System.out.println("第" + code + "个顾客开始获得服务");
Thread.sleep(300);
// 释放一个许可,将其返回给信号量。
semaphore.release();
System.out.println("信号量中当前可用的许可数: "+ semaphore.availablePermits());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
pool.execute(run);
}
// 退出线程池
pool.shutdown();
}
}