首页 > 代码库 > 简单的多线程买票模拟程序(lock解决多线程存在大安全隐患)

简单的多线程买票模拟程序(lock解决多线程存在大安全隐患)

——————————————————————

jdk1.5的lock代替synchronized,condition封装

Object对象里sleep,wait,notify ,notifyAll

——————————————————————

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

*/
import java.util.concurrent.locks.*;
   class Tick implements Runnable{
         private static  int tick=100;
         private String window;
        //创建锁对象
        private Lock lock=new ReentrantLock();
       //通过锁对象来创建Condition对象
       private Condition con=lock.newCondition();
         public  void windowName(String window){
                       this.window=window;
         }
         public void show(Object obj){
            System.out.println(obj);
         }
         public void run(){
                //加锁
                lock.lock();
               try{
                while(tick>0){
                   //相当于以前的锁.sleep(1);
                    con.awaitNanos(1);
                     if(tick>0)
                        show(window+": "+tick--+" 号票");
                 }
               }catch(Exception e ){}
             finally{
                 show(window+": 票已卖完");
                 //解锁
                 lock.unlock();
             }
         }
   }

   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();
          }

   }

简单的多线程买票模拟程序(lock解决多线程存在大安全隐患)