By Bibhab Das
This project helps users to by tickets. In the program, I used Thread Synchronization to avoid ticket conformation confusion.
The project is a simple ticket booking system implemented in Java using threads and synchronization. It consists of three classes: `TicketCounter`, `TicketBookingThread`, and `MainDemo`.
The `TicketCounter` class represents a ticket counter with a certain number of available seats. It has a private member variable `availableSeats` initialized to 3. The `bookTicket` method is defined with the `synchronized` keyword to ensure that only one thread can access it at a time. This method takes a name and the number of seats as input parameters. It checks if the requested number of seats is available and greater than zero. If the conditions are met, it prints a success message and updates the `availableSeats` count accordingly. Otherwise, it prints a failure message indicating that the seats are not available.
The `TicketBookingThread` class extends the `Thread` class and represents a thread responsible for booking tickets. It has member variables `tc` (of type `TicketCounter`), `pname` (representing the person's name), and `num_seats` (indicating the number of seats to book). The constructor initializes these variables. The `run` method overrides the `run` method of the `Thread` class. It calls the `bookTicket` method of the `TicketCounter` object, passing the person's name and the number of seats.
The `MainDemo` class is the entry point of the program. In the `main` method, it creates an instance of the `TicketCounter` class called `tc`. Then it creates three instances of the `TicketBookingThread` class, passing the `tc` object, person's name, and the number of seats for each thread. Finally, it starts all three threads using the `start` method.
When the program runs, each thread executes its `run` method concurrently. The `bookTicket` method of the `TicketCounter` class is synchronized, ensuring that only one thread can access it at a time. This prevents race conditions and ensures that the available seats are correctly updated when multiple threads try to book tickets simultaneously.
Overall, the project demonstrates a simple thread-safe ticket booking system, where multiple threads can book tickets concurrently while ensuring the correct state of the available seats.
in this program Siva requested 2 tickets, Ramesh requested 1 ticket and Bhavani requested 2 tickets, but the number of available seats is 3. So 2 tickets are allocated for Siva, and 1 seat is allocated for Ramesh but now all tickets are booked, so it shows to Bhavani that no seat is available.
Submitted by Bibhab Das (bibhab123)
Download packets of source code on Coders Packet
Comments