BusSeat类:
import java.util.Random;
public class BusSeat implements Runnable {
//定义座位数
int seat = 80;
Random ran = new Random();
@Override
public void run() {
while (seat > 0){
synchronized (" "){
if (seat > 0){
//随机生成上车的人数
int s = ran.nextInt(seat)+1;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
seat -= s;
System.out.println(Thread.currentThread().getName() + "上车-" + s + "人--还剩" +seat + "个座位" );
}
}
}
}
}
TestSeat类:
public class TestSeat {
public static void main(String[] args) {
BusSeat bs = new BusSeat();
Thread t1 = new Thread(bs,"前门");
Thread t2 = new Thread(bs,"中门");
Thread t3 = new Thread(bs,"后门");
t1.start();
t2.start();
t3.start();
}
}