Coach店一般只允许保持不超过某个特定数量的顾客在店里,其余的顾客要在店外等候,直到店里有顾客出来才允许进入,Java中的Semaphore
信号量的用法和这个场景非常相似,下面使用Semaphore仿真顾客逛Coach店的场景。
(1)顾客类Guest:
class="java" name="code">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)));
}
}
}