From dd548e1c661c23174f31faf8c82a86ca13fc3935 Mon Sep 17 00:00:00 2001 From: Aadit Agrawal Date: Mon, 28 Oct 2024 02:14:45 +0530 Subject: [PATCH] Add OOP/Java/Assignments/FISAC/Q9.java --- OOP/Java/Assignments/FISAC/Q9.java | 40 ++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 OOP/Java/Assignments/FISAC/Q9.java diff --git a/OOP/Java/Assignments/FISAC/Q9.java b/OOP/Java/Assignments/FISAC/Q9.java new file mode 100644 index 0000000..432c4c0 --- /dev/null +++ b/OOP/Java/Assignments/FISAC/Q9.java @@ -0,0 +1,40 @@ +import java.util.concurrent.*; +import java.util.*; + +class SeatAlreadyBookedException extends Exception { + SeatAlreadyBookedException(String msg) { super(msg); } +} + +public class SeminarHall { + static final int TOTAL_SEATS = 15; + static Map seats = new ConcurrentHashMap<>(); + + public static void main(String[] args) { + ExecutorService executor = Executors.newFixedThreadPool(20); + for (int i = 1; i <= 15; i++) seats.put(i, "Available"); + for (int i = 0; i < 20; i++) { + int userId = i; + executor.submit(() -> { + try { + bookSeat(userId, "User" + userId, "Aadhar" + userId); + } catch (SeatAlreadyBookedException e) { + System.out.println(e.getMessage()); + } + }); + } + executor.shutdown(); + try { executor.awaitTermination(1, TimeUnit.MINUTES); } catch (InterruptedException e) {} + System.out.println("Final Booking Status: " + seats); + } + + static void bookSeat(int userId, String name, String aadhar) throws SeatAlreadyBookedException { + int seatNumber = (userId % TOTAL_SEATS) + 1; + synchronized (seats) { + if (!seats.get(seatNumber).equals("Available")) { + throw new SeatAlreadyBookedException("Seat " + seatNumber + " already booked by another user."); + } + seats.put(seatNumber, name + " (" + aadhar + ")"); + System.out.println("Seat " + seatNumber + " booked by " + name); + } + } +}