使用Java里的Semaphore信号量模拟顾客逛Coach店

Coach店一般只允许保持不超过某个特定数量的顾客在店里,其余的顾客要在店外等候,直到店里有顾客出来才允许进入,Java中的Semaphore信号量的用法和这个场景非常相似,下面使用Semaphore仿真顾客逛Coach店的场景。
(1)顾客类Guest:
package coachStore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class Guest implements Runnable
{
//Coach店一次允许进入的顾客数量
private static final int SIZE = 10;
private static int count = 0;
private int id = count++;
//允许SIZE个顾客同时访问的信号量
private static Semaphore room = new Semaphore(SIZE, true);
private int shoppingTime;

public Guest(int shoppingTime)
{
this.shoppingTime = shoppingTime;
}
public void run()
{
try
{
System.out.println("Guest " + id + " is waiting for entering the store");
//顾客等待进入Coach店,如果店里的顾客已满,则等待(阻塞)
room.acquire();
System.out.println("Guest " + id + " entered the store and started to look around");
//线程睡眠以模拟顾客在店里逛的动作
TimeUnit.SECONDS.sleep(shoppingTime);
//顾客离开时需要签离,释放一个位置
room.release();
System.out.println("Guest " + id + " stayed for " + shoppingTime + " seconds and left");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}


(2)main类:
package coachStore;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CoachStoreDemo
{
//所有顾客的数量
final static int GUEST_QUANTITY = 100;
private static Random rand = new Random(47);
public static void main(String[] args)
{
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i < GUEST_QUANTITY; i++)
{
//随机生成一个0到10之间的数字表示顾客在店里逗留的时间,启动一个顾客线程
exec.execute(new Guest(rand.nextInt(10)));
}
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值