Add OOP/Java/Assignments/FISAC/Q9.java
This commit is contained in:
parent
35507d524c
commit
dd548e1c66
40
OOP/Java/Assignments/FISAC/Q9.java
Normal file
40
OOP/Java/Assignments/FISAC/Q9.java
Normal file
@ -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<Integer, String> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user