semaphore:信号量,用于控制线程并发访问的资源。
在网上看到个例子写的挺好:将车位比喻为资源,进出的车辆为线程,那么守门人控制车辆进出的人就为信号量的作用。
在网上找到个例子,自己写了下,当作笔记吧
public static void main(String[] args) throws InterruptedException {
// Semaphore sap=new Semaphore(2);
// sap.acquire(2);//获取两个数量,而不是第二个
// System.out.println(sap.tryAcquire());尝试着获取,获取不到则放弃
// System.out.println(sap.isFair());线程访问是否是公平的,即先进先出
// 线程池
ExecutorService exec = Executors.newCachedThreadPool();
// 只能5个线程同时访问
final Semaphore semp = new Semaphore(1);
// 模拟20个客户端访问
for (int index = 0; index < 20; index++) {
final int NO = index;
Runnable run = new Runnable() {
public void run() {
try {
// 获取许可
// boolean flag=semp.tryAcquire(10000, TimeUnit.MILLISECONDS) ;
// System.out.println(flag+"Accessing: " + NO);
semp.acquire();
System.out.println("Accessing: " + NO);
Thread.sleep((long) (Math.random() * 10000));
// 访问完后,释放 ,如果屏蔽下面的语句,则在控制台只能打印5条记录,之后线程一直阻塞
semp.release(); System.out.println(semp.availablePermits()+"==============");
} catch (InterruptedException e) {
}
}
};
exec.execute(run);
}
// 退出线程池
exec.shutdown();
}
注意:开始时是用junit单元测试,测试不成功,后来换到main方法就可以了