本帖最后由 yangcy 于 2014-7-13 16:40 编辑
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- public class ThreadDemo {
- /**
- * 7、 编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、售票窗口、售票中心。售票中心分配一定数量的票,
- * 由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。
- *
- */
- public static void main(String[] args) {
- Thread t1 = new Thread(new SealWindow());
- t1.setName("1号售票窗口");
- Thread t2 = new Thread(new SealWindow());
- t2.setName("2号售票窗口");
- Thread t3 = new Thread(new SealWindow());
- t3.setName("3号售票窗口");
- Thread t4 = new Thread(new SealWindow());
- t4.setName("4号售票窗口");
- Thread t5 = new Thread(new SealWindow());
- t5.setName("5号售票窗口");
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- t5.start();
- }
- }
- class Ticket {
- private int id;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- }
- class SealWindow implements Runnable {
- @Override
- public void run() {
- sellTicket();
- }
- public void sellTicket() {
- TicketSealCenter tsc = TicketSealCenter.getInstance();
- List<Ticket> tickets = tsc.getTickets();
- while (!tickets.isEmpty()) {
- Iterator<Ticket> it = tickets.iterator();
- Ticket ticket = it.next();
- System.out.println(Thread.currentThread().getName() + "...."
- + "卖了一张票,id为" + "..." + ticket.getId());
- tickets.remove(ticket);
- }
- }
- }
- // 只有一个售票中心,所以把它设置成单例
- class TicketSealCenter {
- private static List<Ticket> tickets = new ArrayList<Ticket>();
- private int ticketNum = 100;
- private TicketSealCenter() {
- // 给每张票设置一个唯一的ID号
- setIdToTicket(tickets);
- }
- private static TicketSealCenter tsc = new TicketSealCenter();
- // 提供一个公有方法,获取售票中心对象
- public static TicketSealCenter getInstance() {
- return tsc;
- }
- private void setIdToTicket(List<Ticket> tickets2) {
- for (int i = 1; i <= ticketNum; i++) {
- Ticket ticket = new Ticket();
- ticket.setId(i);
- tickets.add(ticket);
- }
- }
- public List<Ticket> getTickets() {
- return tickets;
- }
- }
复制代码 会出现线程卖的是同一张票。求分析并解决。多谢。
|
|