java--多线程课程源码2--售票系统示例

上一篇 / 下一篇  2010-11-07 21:24:47 / 个人分类:JAVA

class TicketsSystem
{
 public static void main(String[] args)
 {
  SellThread st=new SellThread();
  
  new Thread(st).start();
  try
  {
   Thread.sleep(1);
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
  st.b=true;
  new Thread(st).start();
  //new Thread(st).start();
  //new Thread(st).start();
 }
}

class SellThread implements Runnable
{
 int tickets=100;
 Object bj=new Object();
 boolean b=false;
 public void run()
 {
  if(b==false)
  {
   while(true)
    sell();
  }
  else
  {
   while(true)
   {
    synchronized(obj)
    {
     try
     {
      Thread.sleep(10);
     }
     catch(Exception e)
     {
      e.printStackTrace();
     }
     synchronized(this)
     {
      if(tickets>0)
      {
       
       System.out.println("obj:"+Thread.currentThread().getName()+
         " sell tickets:"+tickets);
       tickets--;
      }
     }
    }
   }
  }
 }
 public synchronized void sell()
 {
  synchronized(obj)
  {
   if(tickets>0)
   {
    try
    {
     Thread.sleep(10);
    }
    catch(Exception e)
    {
     e.printStackTrace();
    }
    System.out.println("sell():"+Thread.currentThread().getName()+
      " sell tickets:"+tickets);
    tickets--;
   }
  }
 }
}


TAG:

 

评分:0

我来说两句

日历

« 2024-05-05  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 86392
  • 日志数: 218
  • 书签数: 1
  • 建立时间: 2010-11-06
  • 更新时间: 2011-03-21

RSS订阅

Open Toolbar