java_简单的售票系统

来源:互联网 发布:mysql 大数据查询 编辑:程序博客网 时间:2024/06/12 00:04

通过对多线程的学习,模拟了一个简单的售票系统


class Ticket implements Runnable
{
 private int tick=TicketSealCenter.num;
 Object obj = new Object();
 public void run()
 {
  while(true)
  {
   synchronized(obj)
   {
    if(tick>0)
    {
     String name = Thread.currentThread().getName();
     int windows = Integer.parseInt(name.substring(7, name.length()));
     try{Thread.sleep(100);}catch(Exception e){}
     System.out.println("第"+(windows+1)+"窗口卖出了第"+tick--+"张票");
    }
   }
   
  }
 }
}
//售票窗口通过for循环控制窗口数量
class SealWindow
{
 public static void addWindow()
 {
  Ticket t = new Ticket();
  for(int x=1;x<=4;x++)
  {
   Thread t1 = new Thread(t);
   t1.start();
  }
 }
}

//售票中心控制票数
class TicketSealCenter
{
 public static int num=100;
}

public class ThreadDemo2
{
 public static void main(String[] args)
 {
  SealWindow.addWindow();
 }
}

 

0 2