一个停车场一共有50个车位, 建立两条线程模拟两个入口. 随机停没有停过车的车位,停完提示车位已满.
public static void main(String[] args) {
new CarStop("入口1").start();
new CarStop("入口2").start();
}
class CarStop extends Thread{
private static int carStop = 50;
ArrayList<Integer> list = new ArrayList<>();
Random r = new Random();
public CarStop(String name) {
super(name);
}
public void run() {
while (true) {
synchronized (CarStop.class) {
if (carStop == 0) {
System.out.println("车位已满");
break;
}
int num = r.nextInt(50)+1;
if (!list.contains(num)) {
list.add(num);
carStop--;
System.out.println("从" + getName() + "进入,停在" + num +"车位还剩" + carStop + "个车位");
}
}
}
}
}
|
|