About
SET => 1
class TicketBookingSystem { private int availableTickets;
public TicketBookingSystem(int availableTickets) {
this.availableTickets = availableTickets;
}
public synchronized void bookTickets(int requestedTickets, String customerName) {
if (requestedTickets <= availableTickets) {
System.out.println(customerName + " booked " + requestedTickets + " tickets.");
availableTickets -= requestedTickets;
} else {
System.out.println("Insufficient tickets. " + customerName + " could not book tickets.");
}
}
}
class Customer implements Runnable { private String name; private int requestedTickets; private TicketBookingSystem bookingSystem;
public Customer(String name, int requestedTickets, TicketBookingSystem bookingSystem) {
this.name = name;
this.requestedTickets = requestedTickets;
this.bookingSystem = bookingSystem;
}
public void run() {
bookingSystem.bookTickets(requestedTickets, name);
}
}
public class Main { public static void main(String[] args) { TicketBookingSystem bookingSystem = new TicketBookingSystem(10);
// Create three customer threads
Customer customer1 = new Customer("Customer 1", 4, bookingSystem);
Customer customer2 = new Customer("Customer 2", 3, bookingSystem);
Customer customer3 = new Customer("Customer 3", 5, bookingSystem);
Thread thread1 = new Thread(customer1);
Thread thread2 = new Thread(customer2);
Thread thread3 = new Thread(customer3);
// Start all customer threads
thread1.start();
thread2.start();
thread3.start();
}
}
SET 2 =>
class BankAccount { private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public synchronized void deposit(double amount) {
balance += amount;
}
public synchronized double inquire() {
return balance;
}
}
class Customer implements Runnable { private String name; private double amount; private BankAccount account;
public Customer(String name, double amount, BankAccount account) {
this.name = name;
this.amount = amount;
this.account = account;
}
public void run() {
account.deposit(amount);
System.out.println(name + " deposited $" + amount);
System.out.println(name + "'s balance: $" + account.inquire());
}
}
public class Main { public static void main(String[] args) { BankAccount account = new BankAccount(1000);
// Create three customer threads
Customer customer1 = new Customer("Customer 1", 500, account);
Customer customer2 = new Customer("Customer 2", 300, account);
Customer customer3 = new Customer("Customer 3", 200, account);
Thread thread1 = new Thread(customer1);
Thread thread2 = new Thread(customer2);
Thread thread3 = new Thread(customer3);
// Start all customer threads
thread1.start();
thread2.start();
thread3.start();
}
}