- 停车场中有三个停车位。
- 车辆可以实现停车(假定停车时间为10秒)和离开停车位的动作。
- 使用多线程模拟实现多辆车停车。停车成功显示:xxx号车成功停止在xxx号停车位;如果该停车位已满则停车失败。
class Park implements Runnable {
private boolean space = false;
Object obj = new Object();
static int n = 1;
public Park(boolean space) {
this.space=space;
}
@Override
public void run() {
while(true) {
synchronized (obj) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(n<=3) {
System.out.println("停车成功:" + Thread.currentThread().getName() + "成功停止在" + n + "号停车位");
n++;
}else {
System.out.println("停车失败");
Thread.currentThread().interrupt();
break;
}
if(space==true) {
Thread.currentThread().interrupt();
System.out.println(Thread.currentThread().getName()+"已离开"+n+"号车位");
n--;
}
}
break;
}
}
}
public class MySQLPark {
public static void main(String[] args) {
Park p = new Park(false);
Thread t = new Thread(p, "1号车");
Thread t1 = new Thread(p, "2号车");
Thread t2 = new Thread(p, "3号车");
Thread t3 = new Thread(p, "4号车");
t.start();
t1.start();
t2.start();
t3.start();
}
}