模拟多人售票的多线程测试

 

01class LockDemo{
02    public static void main(String [] hello){
03        TestThread tt = TestThread.getInstance_robot();
04        new Thread(tt).start(); //on work ,here comes a client saler A
05        try{Thread.sleep(10);}catch(Exception e){}
06  
07        tt.lockname = "Vip_clinet1"; //saler B was late for work,but 
08                     //later is better than never
09        new Thread(tt).start();
10    }
11}
12  
13class TestThread implements Runnable{
14      
15    private int how_many; //counter
16    private static TestThread FC_instance = null;
17  
18    //singleton it~
19    private TestThread(){
20        this.how_many = 0;
21    }
22  
23    public static TestThread getInstance_robot(){
24    if(FC_instance == null)
25        return new TestThread();
26    return FC_instance;
27    }
28  
29    String lockname = "iamalock hahahaha~";
30    int tickets = 1200; //assume there is 1200 
31    //railway ticket waiting to get saled by
32    //2 operators in the station's terminal windows
33      
34    public void run(){
35      
36    int tickets_flag = this.tickets;
37      
38    if(lockname.equals("Vip_clinet1"))
39    {
40        while(true){
41            if(tickets > 0 ){
42                    try{Thread.sleep(1);}/**VIP嘛 当然要慢那么一点点了哦..*/catch(Exception e){}
43                    synchronized(lockname){};
44                    System.out.println("| "+this.lockname+" is saling ticket: "+tickets--+" | ");
45            }
46        }
47    }else //anoymous robot saler -_-*)
48    {
49        while(true){//我要风了,,,还是处理不好CPU时间片儿的问题阿
50            synchronized(lockname){
51                if(tickets > 0){
52                    try{Thread.sleep(3);}catch(Exception e){}
53                    synchronized(lockname){};
54                    System.out.println("\t\t\t\t\t | "+Thread.currentThread().toString()+" is saling tickets "+tickets--+" | ");
55    how_many++;
56                }else 
57                {
58                System.out.println(tickets_flag+"张票 全部受完\t打烊!");
59                System.out.println("报告长官:VIP售出"+(tickets_flag-how_many)+" 张票\n");
60                System.out.println("机器人员工售出:"+how_many+"张票\n");
61              
62                //try{Thread.stop(this);}catch(Exception e){}
63                return;
64                }
65            }        
66        }
67    }
68  
69    }//end function run()
70

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值