Java多线程编程,模拟售票

package ticktester;
02 class Ticket{
03     private int ticketCount;
04      
05     public Ticket(int ticketCount){
06         this.ticketCount = ticketCount;
07     }
08      
09     public synchronized void withBuyTicket(int amount){
10         int currentTicketAmount = ticketCount;
11          
12         System.out.println("\n目前票数:"+currentTicketAmount);
13         if(currentTicketAmount==0)
14         {
15             System.out.println("票已全部售出!");
16             return;
17         }
18         if(amount>currentTicketAmount)
19         {
20             System.out.println("需售出票数: "+amount+" 剩下票数为: "+currentTicketAmount+" 剩余票数不足 !");
21         }
22         else   
23         {
24             currentTicketAmount = currentTicketAmount-amount;
25             System.out.println("售出票数:"+amount+" 剩余票数: "+currentTicketAmount);
26             ticketCount = currentTicketAmount;
27         }
28     }
29 }
30  
31 class BuyTicket implements Runnable{
32     private Ticket t;
33     private int amount;
34      
35     public BuyTicket(Ticket t,int amount){
36         this.t = t;
37         this.amount = amount;
38     }
39      
40     public void run(){
41         try {
42             Thread.sleep(((int)(Math.random()*10000)));
43     } catch (InterruptedException e) {
44             e.printStackTrace();
45     }
46         t.withBuyTicket(amount);
47     }
48 }
49  
50 public class TickTester {
51  
52     /**
53      * @param args
54      */
55     public static void main(String[] args) {
56         // TODO Auto-generated method stub
57         Ticket t = new Ticket(10);
58         BuyTicket a1 = new BuyTicket(t,2);
59         BuyTicket a2 = new BuyTicket(t,2);
60         BuyTicket a3 = new BuyTicket(t,1);
61         BuyTicket a4 = new BuyTicket(t,1);
62         BuyTicket a5 = new BuyTicket(t,2);
63         BuyTicket a6 = new BuyTicket(t,3);
64         Thread tk1 = new Thread(a1);
65         Thread tk2 = new Thread(a2);
66         Thread tk3 = new Thread(a3);
67         Thread tk4 = new Thread(a4);
68         Thread tk5 = new Thread(a5);
69         Thread tk6 = new Thread(a6);
70         tk1.start();
71         tk2.start();
72         tk3.start();
73         tk4.start();
74         tk5.start();
75         tk6.start();
76     }
77 }

你可能感兴趣的:(java多线程)