Semaphore

mac2025-05-26  31

关于Semaphore的使用介绍 1.什么是Semaphore Semaphore是一个计数信号量,通常用于限制对某些资源访问的线程数量,Semaphore管理一系列许可证。举个栗子:

假如我们要去游泳池游泳,泳池一共有6条泳道,每条泳道只能有1个人在上面使用。每个人去游泳之前要先 acquire() 一下获取许可证,如果有空闲泳道就可以去游泳;如果没有空闲泳道,就只能阻塞等待。游完泳之后,再 release() 一下释放许可证,释放出该泳道的使用权,确保下一个人 acquire() 的时候可以获取可用泳道,继续游泳。如果泳道上都有人了,再有人过来游泳,就需要等待其他人。 这个泳道的数量,我们是可以自行设定的。这里的泳池就是共享资源,而泳道的数量就是可访问的线程数量,游泳者就是线程。 2.实例10个人去银行办理业务,只有两个窗口

package IO; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; /** * @author 犀角 * @date 2019/11/1 11:23 * @description 假设10个人在银行办理业务,只有2个工作窗口,使用Semaphore类 */ public class SemaphoreDemo { // 排队总人数(请求总数) private static int clientTotal = 10; //可同时受理业务的窗口数量(同时并发执行的线程数) public static int threadTotal = 2; public static void main(String[] args) { // 创建缓存线程池 ExecutorService executorService = Executors.newCachedThreadPool(); final Semaphore semaphore = new Semaphore(threadTotal); final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); for (int i = 0;i<clientTotal;i++){ final int count = i; executorService.execute(()->{ try { semaphore.acquire(); System.out.println("服务号{"+count+"},受理业务中。。。"); Thread.sleep(1000); semaphore.release(2); } catch (InterruptedException e) { System.out.println("exception"+e); } countDownLatch.countDown(); }); } } }

 

最新回复(0)