- /*
- * Ticket: 属性:编号(代表第几张票) 行为:打印票据信息(重写toString方法)
- */
- public class Ticket {
- private int num;
- public Ticket(int num) {
- this.num = num;
- }
-
- @Override
- public String toString() {
- return "黑马大电影:" + num + "号票";
- }
- }
复制代码- public class SealWindow implements Runnable {
-
- private TicketSealCenter tickets;
- public SealWindow(TicketSealCenter tickets) {
- this.tickets = tickets;
- }
- @Override
- public void run() {
- while(tickets.hasTicket()) {
- synchronized(tickets) {
- if(!tickets.hasTicket()) {
- break;
- }
- Ticket t = tickets.sellTicket();
- System.out.println(Thread.currentThread().getName() + "卖出了 : " + t);
- }
- }
- }
- }
复制代码- import java.util.LinkedList;
- /*
- * TicketSealCenter:
- * 售票中心应该持有所有的票对象,定义一个集合用来存储票对象,由于票不能重复,因此使用Set集合
- * 属性:Set<Ticket>集合用于存储所有票的信息
- * int number 定义初始的票的数量
- * 在构造方法中对集合进行初始化,即对票进行编号,票的数量从外界获取
- */
- public class TicketSealCenter {
- private LinkedList<Ticket> tickets = new LinkedList<>();
-
- public TicketSealCenter(int num) {
- for (int i = 1; i <= num ; i++) {
- tickets.add(new Ticket(i));
- }
- }
-
- public Ticket sellTicket() {
- return tickets.remove();
- }
-
- public boolean hasTicket() {
- return !tickets.isEmpty();
- }
- }
复制代码 |
|