java --thread--火车票售票系统

来源:互联网 发布:adb mac最新版本 编辑:程序博客网 时间:2024/05/21 11:12

public class testTickts {
 
 public static void main(String [] args)
 {
  tickts mt = new tickts();
  new Thread(mt).start();
  try
  {
   Thread.sleep(1000);
  }
  catch(Exception e)
  {
   
  }
  
  
  mt.b=true;
  new Thread(mt).start();
 // new Thread(mt).start();
 // new Thread(mt).start();
 }
}


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

   }
   System.out.println("this"+ Thread.currentThread().getName()
     + "sells ticks: " + ticks);
   ticks--;
  }
 }
}

原创粉丝点击