首页 > 编程语言 > 详细

简单的多线程买票模拟程序

时间:2016-10-01 14:57:59      阅读:329      评论:0      收藏:0      [点我收藏+]

/*
  需求:
  写一个简单的多线程模拟买票的程序
  四个买票窗口,一共有100张票

*/

   class Tick implements Runnable{
         private static  int tick=100;
         private String window;
         public  void windowName(String window){
                 synchronized(Tick.class){
                    try{
                       Thread.sleep(1);
                      }catch(Exception e){}
                      
                       this.window=window;
                  }
         }
         public void show(Object obj){
            System.out.println(obj);
         }
         public void run(){
             while(tick>0){
                 synchronized(Tick.class){
                    try{
                       Thread.sleep(10);
                      }catch(Exception e){}
                      
                     if(tick>0)
                        show(window+": "+tick--+" 号票");
                     else
                         show(window+": 票已卖完");

                  }
             }
         }
   }

   public class TicketDemo{
          public static void main(String args[]){

               Tick tick0=new Tick();
               Tick tick1=new Tick();
               Tick tick2=new Tick();
               Tick tick3=new Tick();
               Thread t0=new Thread(tick0);
               Thread t1=new Thread(tick1);
               Thread t2=new Thread(tick2);
               Thread t3=new Thread(tick3);
               tick0.windowName("窗口1");
               tick1.windowName("窗口2");
               tick2.windowName("窗口3");
               tick3.windowName("窗口4");
               t0.start();
               t1.start();
               t2.start();
               t3.start();
          }

   }

简单的多线程买票模拟程序

原文:http://www.cnblogs.com/heji/p/5925744.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!