importjava.util.Random;importjava.util.concurrent.ArrayBlockingQueue;importjava.util.concurrent.BlockingQueue;importjava.util.concurrent.Semaphore;importjava.util.concurrent.SynchronousQueue;importsun.awt.geom.AreaOp.IntOp;/***
*@authorAdministrator
* 多线程停车系统模型*/
public classtest2 {//private static final SynchronousQueue sq = new SynchronousQueue();//新建5个停车位
Random random = newRandom();private static final BlockingQueue carPakingSpace = new ArrayBlockingQueue(5);//private void parkingSeat(String cars) {//System.out.println(cars+"停车");//}
public static voidmain(String[] args) {newtest2().Cars();
}//车位系统//privat5e void//初始化车辆
private voidCars() {//现有20辆车子要来停车,但是每1秒只能停1辆车子
final Semaphore _Semaphore = new Semaphore(1);for(int i=0 ; i<20; i++) {new Thread(newRunnable() {public voidrun() {//while(true) {
try{
_Semaphore.acquire();
pakingCars(Thread.currentThread().getName());//每一秒只能停1辆车
Thread.sleep(1000);
_Semaphore.release();//模拟停车的时间
Thread.sleep(random.nextInt(4000)+1000);//离开了
leaveCars(Thread.currentThread().getName());
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}//准备离开的车
private voidleaveCars(String cars) {try{
System.out.println(carPakingSpace.take()+"-----离开了");
}catch(InterruptedException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}//停车
private voidpakingCars(String cars) {try{
carPakingSpace.put(cars);
System.out.println(cars+": 停车");
}catch(InterruptedException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
}