package com.swift; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TicketSaleCenter { public static void main(String[] args) { /* * 第6题: 编写三各类Ticket、SaleWindow、TicketSaleCenter分别代表票信息、售票窗口、售票中心。 * * 售票中心分配一定数量的票,由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。 */ Ticket tic = new Ticket(); tic.setTotal_num(1000); SaleWindow win = new SaleWindow(tic); Thread t1 = new Thread(win, "售票窗1"); Thread t2 = new Thread(win, "售票窗2"); Thread t3 = new Thread(win, "售票窗3"); t1.start(); t2.start(); t3.start(); } } class Ticket { private int total_num; private int sold_num; public int getTotal_num() { return total_num; } public void setTotal_num(int total_num) { this.total_num = total_num; } public int getSold_num() { return sold_num; } public void setSold_num(int sold_num) { this.sold_num = sold_num; } } class SaleWindow implements Runnable { private Ticket tic; public Ticket getTic() { return tic; } public void setTic(Ticket tic) { this.tic = tic; } public SaleWindow(Ticket tic) { super(); this.tic = tic; } @Override public void run() { while (true) { synchronized ("锁") { int totalNum = tic.getTotal_num(); int soldNum = tic.getSold_num(); if (totalNum > 0) { totalNum--; tic.setTotal_num(totalNum); soldNum++; tic.setSold_num(soldNum); System.out.println(Thread.currentThread().getName() + " 已卖出第 " + tic.getSold_num() + " 张票," + "剩余的票数是 " + tic.getTotal_num()); } } } } }