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 }
利用多线程实现的简单模拟卖票。
posted @ 2015-09-02 20:02  邻家小书童  阅读(528)  评论(0编辑  收藏  举报