package com.itheima;
public class Test28 {
public static void main(String[] args) {
Test28 t = new Test28();
t.new Ticket();
}
class Ticket {
public Ticket() {
TicketSealCenter tsc = new TicketSealCenter(100);// 定义有100张票
for (int i = 0; i < 5; i++) {// 定义有5个窗口
new Thread(new SealWindow(i, tsc)).start();// 启动售票窗口售票
}
}
}
/**
* 售票中心类 定义了票的总数,同步售票方法
*/
class TicketSealCenter {
int ticketNum = 50;
boolean flag = false; // 定义票是否卖完
public TicketSealCenter(int num) {// 定义一个改变票数的方法
this.ticketNum = num;
}
public synchronized void sellTicket(SealWindow s) {
if (ticketNum > 0) {//票数如果大于0
int n = s.num + 1;//n表示第几号窗口
System.out
.println("第--" + n + "--售票窗口卖出了第" + ticketNum + "张票!");
ticketNum--;//卖出一张票后减1
} else {
flag = true;
}
}
}
/**
* 售票窗口类
*/
class SealWindow implements Runnable {
int num;//num表示第几号窗口-1,即i
TicketSealCenter tsc;
public SealWindow(int num, TicketSealCenter tsc) {
this.num = num;
this.tsc = tsc;
}
public final void run() {
while (!tsc.flag) {
tsc.sellTicket(this); // 调用售票中心类的同步票数
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
|
|