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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单的多线程买票模拟程序相关的知识,希望对你有一定的参考价值。

/*
  需求:
  写一个简单的多线程模拟买票的程序
  四个买票窗口,一共有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();
          }

   }

以上是关于简单的多线程买票模拟程序的主要内容,如果未能解决你的问题,请参考以下文章

多线程(模拟买票)-----java基础知识总结

Java多线程同步锁的理解

多线程同步-买票系统

多线程编程

线程模拟买票

多线程