class Ticket implements Runnable{

 private int TicketNum = 100; //100张火车票
 private boolean flag = true;
 private synchronized void sale()
 {
  if(TicketNum<=0)
  {
   flag = false;
   return ;
  }
  TicketNum--;
  System.out.println(Thread.currentThread().getName()+"卖了一张票,还剩"+TicketNum+"张票。");
 }
 
 @Override
 public void run() {
  // TODO Auto-generated method stub
     
  while(flag)
  {
   sale();

   Java多线程小例子(三个窗口卖火车票)

 

   try {

    Thread.sleep(200);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 
}

public class SaleTicket {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
       Ticket t = new Ticket();
       Thread th1 = new Thread(t,"窗口A");
       Thread th2 = new Thread(t,"窗口B");
       Thread th3 = new Thread(t,"窗口C");
      
       th1.start();
       th2.start();
       th3.start();
      
 }

}

相关文章:

  • 2021-11-29
  • 2021-08-14
  • 2021-12-30
  • 2022-12-23
  • 2022-12-23
  • 2021-04-04
  • 2022-12-23
  • 2022-02-14
猜你喜欢
  • 2022-12-23
  • 2022-02-09
  • 2022-02-05
  • 2021-06-26
  • 2022-12-23
  • 2022-01-05
  • 2022-12-23
相关资源
相似解决方案