public class DepositoConAttesa {
    private Integer prodotto;

    public synchronized void inserisci(int numero) throws InterruptedException {
        while (prodotto != null) {
            wait();
        }
        prodotto = numero;
        notifyAll();
    }

    public synchronized int preleva() throws InterruptedException {
        while (prodotto == null) {
            wait();
        }
        int numero = prodotto;
        prodotto = null;
        notifyAll();
        return numero;
    }

    public static void main(String[] args) throws InterruptedException {
        DepositoConAttesa deposito = new DepositoConAttesa();
        Thread produttore = Thread.ofPlatform().start(() -> {
            try {
                for (int numero = 0; numero < 5; numero++) {
                    deposito.inserisci(numero);
                }
                deposito.inserisci(-1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        Thread consumatore = Thread.ofPlatform().start(() -> {
            try {
                while (true) {
                    int numero = deposito.preleva();
                    if (numero == -1) {
                        break;
                    }
                    System.out.println("prelevato: " + numero);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        produttore.join();
        consumatore.join();
    }
}
