/**
*
* 1、有一辆班车除司机外只能承载80个人,假设前中后三个车门都能上车,如果坐满则不能再上车。
* 请用线程模拟上车过程并且在控制台打印出是从哪个车门上车以及剩下的座位数。 比如: (前门上车---还剩N个座...)
*
*/
public class HomeWork1 {
public static void main(String[] args) {
//创建一个班车对象,传入3个线程
Car c = new Car();
Thread t1 = new Thread(c, "前门");
Thread t2 = new Thread(c, "中门");
Thread t3 = new Thread(c, "后门");
t1.start();
t2.start();
t3.start();
}
}
//班车类
class Car implements Runnable {
private int seatNum = 80;//所剩座位
@Override
public void run() {
while (true) {
// 使用使用当前对象作为同步锁
synchronized (this) {
if (seatNum < 1) {
System.out.println("座位已满,请乘坐下班车!");
break;
} else {
System.out.println(Thread.currentThread().getName() + "上车,还剩" + (--seatNum) + "个座位!");
}
}
}
}
}