Условие
 
Необходимо реализовать систему бронирования товаров на складе в многопоточной среде.
 
На складе находятся товары с уникальными идентификаторами и определённым количеством доступных единиц.
 
Пользователь может одновременно забронировать два разных товара в указанном количестве. Если хотя бы одного товара недостаточно, бронирование должно быть полностью отклонено.
 
public class Product {
private final long id;
private int quantity;
 
public Product(){
if(quantity < 0) {
throw new IllegalArgumentException("Invalid quantity");
}
 
this.id = id;
this.quantity = quantity;
}
 
public long getId(){
return id;
}
 
public synchronized int getQuantity(){
return quantity;
}
 
public synchronized void recieveGoods(int amount){
 
if(amount <= 0){
throw new IllegalArgumentException("Invalid amount");
}
quantity += amount;
}
 
public synchronized void sheepGoods(int amount){
 
if(amount <= 0 ){
throw new IllegalArgumentException("Invalid amount");
}
if(amount > quantity){
throw new IllegalArgumentException("Insufficient amount");
}
quantity -= amount;
 
}
 
}
public class ReservationService {
 
public boolean reserve (Product first,int firstQuantity, Product second, int secondQuantity){
 
if(first == null || second == null){
throw new IllegalArgumentException("Invalid product");
}
 
if(first == second || second.getId() == first.getId()){
throw new IllegalArgumentException("Same product");
}
if(firstQuantity > first.getQuantity() || secondQuantity > second.getQuantity()) {
throw new IllegalArgumentException("Invalid amount");
}
 
if(first.getId() < second.getId()){
doDeal(first,second, first,firstQuantity, second,secondQuantity );
}
else{
doDeal(second, first, first,firstQuantity, second,secondQuantity )
}
 
 
}
 
private void doDeal(Product firstBlock, Product secondBlock, Product first, int firstQuantity, Product second, int secondQuantity){
 
synchronized(firstBlock){
ыни
 
 
}
}
 
 
}
 
 
TryCode — realtime collaborative code editor | product.java