实验任务详情:
完成火车站售票程序的模拟。
要求:
(1)总票数1000张;
(2)10个窗口同时开始卖票;
(3)卖票过程延时1秒钟;
(4)不能出现一票多卖或卖出负数号票的情况。
public class MyThread implements Runnable{
private int tickets=1000;
public int getTickets() {
return tickets;
}
public void setTickets(int tickets) {
this.tickets = tickets;
}
public void run() {
while(true) {
synchronized(this){
try {
if(tickets>0) {
System.out.println(Thread.currentThread().getName()+":是第 "+tickets+" 张票 ");
tickets--;
}
Thread.sleep(1000);
}catch(Exception e) {
System.out.println(e.getMessage());
}
}
if(tickets<=0){
break;
}
}
}
}
public class Text9 {
public static void main(String[] args) {
MyThread mt=new MyThread();
new Thread(mt,"窗口1").start();
new Thread(mt,"窗口2").start();
new Thread(mt,"窗口3").start();
new Thread(mt,"窗口4").start();
new Thread(mt,"窗口5").start();
new Thread(mt,"窗口6").start();
new Thread(mt,"窗口7").start();
new Thread(mt,"窗口8").start();
new Thread(mt,"窗口9").start();
new Thread(mt,"窗口10").start();
}
}