天天看點

java多線程實作賣票小程式 - 鄰家小書童

java多線程實作賣票小程式

1 package shb.java.demo;
 2 /**
 3  * 多線程測試賣票小程式。
 4  * @Package:shb.java.demo
 5  * @Description:
 6  * @author shaobn
 7  * @Date 2015-9-2下午7:49:53
 8  */
 9 public class TestSyn {
10     public static void main(String[] args) {
11         //此注釋為實作方式一
12         /*TicketDemo td = new TicketDemo();
13         Thread t1 = new Thread(td);
14         Thread t2 = new Thread(td);
15         t1.start();
16         t2.start();*/
17         //為實作方式二
18         TicketDemo2 td2 = new TicketDemo2();
19         Thread t3 = new Thread(td2);
20         Thread t4 = new Thread(td2);
21         t3.start();
22         t4.start();
23     }
24 }
25 /**
26  * 賣票的類(實作方式一)
27  * @Package:shb.java.demo
28  * @Description:
29  * @author shaobn
30  * @Date 2015-9-2下午7:44:45
31  */
32 class TicketDemo implements Runnable{
33     private int ticket = 200;
34     public void run(){
35         while(true){
36             synchronized(this){
37             if(ticket>0){
38                 try {
39                     Thread.sleep(100);
40                 } catch (Exception e) {
41                     // TODO: handle exception
42                     e.printStackTrace();
43                 }
44                 System.out.println(Thread.currentThread()+"***"+"票數為"+ticket--);
45             }
46             }            
47         }        
48     }
49     
50 }
51 /**
52  * 賣票的類(實作方式二)
53  * @Package:shb.java.demo
54  * @Description:
55  * @author Shihaobin
56  * @Date 2015-9-2下午7:51:56
57  */
58 class TicketDemo2 implements Runnable{
59     public int ticket = 200;
60     public void run(){
61         while(true){
62             show();    
63         }
64     }
65     //實作對多線程程式的封裝
66     public synchronized void show(){
67         if(ticket>0){
68             try {
69                 Thread.sleep(100);
70             } catch (Exception e) {
71                 // TODO: handle exception
72                 e.printStackTrace();
73             }
74             System.out.println(Thread.currentThread()+"***"+"票數為"+ticket--);
75         }
76         
77     }
78 }
利用多線程實作的簡單模拟賣票。