火车售票模拟程序(多线程) ,有朋友说代码和结果有问题,请指教

去哪儿了 发布于 2014/05/20 11:29
阅读 172
收藏 4
01 package com.test;
02  
03 /**
04  * 测试类
05  * @author administrator
06  *
07  */
08 public class SaleTicket {
09     public static void main(String[] args) {
10         Ticket ticket =new Ticket(20);
11         for (int i = 0; i < 5; i++) {//5个线程
12             new Thread(new Seller(ticket),String.valueOf(i)).start();//线程启动
13         }
14     }
15  
16 }
17 /**
18  * 卖票线程类
19  * @author administrator
20  *
21  */
22 class Seller implements Runnable{
23     Ticket ticket;
24     public Seller(Ticket ticket) {
25         // TODO Auto-generated constructor stub
26         this.ticket =ticket ;
27     }
28     @Override
29     public void run() {
30         // TODO Auto-generated method stub
31         while (ticket.has) {//如果有票继续售,否则终止售票
32             ticket.sellerTicket();//
33             try {
34                 Thread.sleep(100);
35             } catch (InterruptedException e) {
36                 // TODO Auto-generated catch block
37                 e.printStackTrace();
38             }
39         }
40     }
41 }
42 /**
43  * 定义票信息类
44  * @author administrator
45  *
46  */
47 class Ticket {
48     private int ticketCount;
49     protected boolean has=true ;//是否有票
50     public Ticket(int ticketCount) {
51         // TODO Auto-generated constructor stub
52         this.ticketCount=ticketCount;
53     }
54     public synchronized void sellerTicket() {
55         if(ticketCount>0){
56             System.out.println(Thread.currentThread().getName()+"窗口卖第"+ticketCount+"张票");
57             ticketCount--;
58         }else{
59             System.out.println("票已经售完!");
60             has=false;//票已售完
61         }
62     }
63      
64 }//end
65  
66 //输出结果
67  
68 2窗口卖第29张票
69 1窗口卖第28张票
70 3窗口卖第27张票
71 4窗口卖第26张票
72 0窗口卖第25张票
73 2窗口卖第24张票
74 1窗口卖第23张票

加载中
返回顶部
顶部