using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

public class SeatBookingApp
{
    static void Main(string[] args)
    {
        int[] seats=new int[1000];
	  	for (int j=0; j<1000; j++)
	        seats[j]=0;
    	BookingAgent[] b=new BookingAgent[10];
    	SeatBookings s=new SeatBookings(seats);
        Thread[] bookingThreads= new Thread[10];
	  	for (int i=0; i<10; i++)
	  	{
            b[i] = new BookingAgent(s, i);
            bookingThreads[i]=new Thread(new ThreadStart(b[i].bookSeat));
            bookingThreads[i].Name = "Booking agent " + i;
	    	
	    /*	if (i%2==0)
  	      	    bookingThreads[i].Priority=ThreadPriority.Highest;
	    	else
  	      		bookingThreads[i].Priority=ThreadPriority.Lowest; */
            bookingThreads[i].Start();	  	
        }
    }
}

class SeatBookings
{
    private int[] seats;
    public int totalBooked = 0;

    public SeatBookings(int[] s)
    {
        seats = s;
    }

    public bool isAvailable(int seatno)
    {
        return (seats[seatno] == 0);
    }

    public void bookSeat(int seatno)
    {
        Monitor.Enter(this);
        if (isAvailable(seatno))
        {
            Thread.Sleep(1);
            seats[seatno]++;
            totalBooked++;
            Console.WriteLine("Seat " + seatno + " booked. Total booked= " + totalBooked);
        }      
        Monitor.Exit(this);
    }

    public bool doubleBooked(int seatno)
    {
        return (seats[seatno] > 1);
    }
}

class BookingAgent 
{
    private SeatBookings sb;
    private int agent;
    private Random randomNumers=new Random();

  public BookingAgent(SeatBookings s, int a)
  {
        sb=s;
        agent=a;
  }

  public int getAgent() { return agent; }

  public void bookSeat()
  {
    do
    {
        int seatno = (int)(randomNumers.Next(0, 1000));

        sb.bookSeat(seatno);

        if (sb.doubleBooked(seatno))
            Console.WriteLine("Seat number " + seatno + " double booked!");        
    } while (sb.totalBooked<1000);

    Console.WriteLine("All bookings complete");
  }
}


