package com.heima
public class Test2 {
/**
*一辆公交车有70个座位,只能从前后上车,用多线程模拟这个 过程,
*并且输出剩下的座位
*/
public static void main(String[] args) {
System.out.println("一辆公交车有70个座位");
Car c = new Car();
Thread th1 = new Thread(c);
Thread th2 = new Thread(c);
th1.setName("从前门");
th2.setName("从后门");
th1.start();
th2.start();
}
}
class Car implements Runnable{
private int num = 70;
@Override
public void run() {
while(true){
synchronized (Car.class) {
if (num <=0) {
break;
}
System.out.println(Thread.currentThread().getName() + "上车:" + (70- num +1) +"人,还剩:" + (--num ) + "个位置");
}
}
}
} |