-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCantinaVino.java
78 lines (61 loc) · 2.62 KB
/
CantinaVino.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.Random; //cosi importo la libreria che genera numeri casuali
public class CantinaVino {
private static final int numeroDeiBevitori = 10;
private static final int tempoAttesaMassimo = 5000;
private static final int tempoBevutaMassimo = 2000;
private static int vinoRimanente = 100;
private static int rubinettiDisponibili = 3;
private static final Object lock = new Object();
private static class Bevitore extends Thread {
private final int id;
public Bevitore(int id) {
this.id = id;
}
@Override
public void run() {
Random rand = new Random();
boolean staBevendo = true;
while (staBevendo) {
try {
Thread.sleep(rand.nextInt(tempoAttesaMassimo));
synchronized (lock) {
if (rubinettiDisponibili == 0) {
System.out.println("Bevitore " + id + " è in attesa dei rubineti.");
lock.wait();
}
if (vinoRimanente > 0) {
System.out.println("Bevitore " + id + " sta bevendo.");
vinoRimanente--;
rubinettiDisponibili--;
Thread.sleep(rand.nextInt(tempoBevutaMassimo));
rubinettiDisponibili++;
System.out.println("Bevitore " + id + " a finito di bere. Vino rimanente: " + vinoRimanente);
lock.notifyAll();
} else { // cosi con u cout mostro chi è l'ultimo ad aver finito
System.out.println("Bevitore " + id + " ha finito tutto il vino.");
staBevendo = false;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// il main l'ho fatto qui per comodita mia
public static void main(String[] args) {
Thread[] bevitori = new Thread[numeroDeiBevitori];
for (int i = 0; i < numeroDeiBevitori; i++) {
bevitori[i] = new Bevitore(i + 1);
bevitori[i].start();
}
for (int i = 0; i < numeroDeiBevitori; i++) {
try {
bevitori[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Tutti i bevitori hanno finito");
}
}