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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单的多线程买票模拟程序(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解决多线程存在大安全隐患)的主要内容,如果未能解决你的问题,请参考以下文章

synchronized (lock) 买票demo 线程安全

线程模拟买票

如何解决数组上的多线程问题

2Lock锁 (重点)

2Lock锁 (重点)

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