}
}
四,测试类,编写buyPiao方法,创建semaphore对象,使用executors创建线程池,for循环里开启线程,传入我们创建的接口,模拟多个人排队买票
public class SemaphoreDemo {
public static void main(String[] args) {
SemaphoreDemo semaphoreDemo = new SemaphoreDemo();
semaphoreDemo.buyPiao();
}
public void buyPiao(){
//控制并发数,保证同一时间只能有3个人占有窗口
final Semaphore s = new Semaphore(3);
ExecutorService executorService = Executors.newCachedThreadPool();
//模拟20个人购票
for (int i=1;i<=20;i++){
executorService.execute(new Myrunable(s,i));
}
executorService.shutdown();
}