9.有一车票代售点,有4个窗口代售火车票,假设一共有100张(编号1—100)火车票要售出。设计一个多线程程序,模拟车票代售点的售票过程。要求如下:
1)、用4个其他线程分别模拟4个窗口的售票过程。
2)、要求打印出每次所卖出的车票的票号。(如 “第1窗口卖出第3张火车票” )
3)、每次卖出车票后都要休息一下。
package work;
public class Testone {
public static void main(String[] args) {
Sell s = new Sell();
Thread t1 = new Thread(s);
t1.setName("窗口1");
Thread t2 = new Thread(s);
t2.setName("窗口2");
Thread t3 = new Thread(s);
t3.setName("窗口3");
Thread t4 = new Thread(s);
t4.setName("窗口4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Sell implements Runnable{
int num = 100;
boolean flag = true;
public void run() {
while(flag == true) {
synchronized(this) {
if(num>0) {
try {
Thread.sleep(100);
}
catch(InterruptedException e) {
System.out.println(e);
}
System.out.println(Thread.currentThread().getName()+"sell tickets:"+(100-num+1));
num--;
}
else if(num == 0) {
if(flag) {
System.out.println("没有票了");
flag = false;
}
}
}
}
}
}