-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiGruas.java
More file actions
74 lines (61 loc) · 1.92 KB
/
ApiGruas.java
File metadata and controls
74 lines (61 loc) · 1.92 KB
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
package cc.controlReciclado;
import es.upm.babel.cclib.Semaphore;
import es.upm.babel.cclib.ConcIO;
import java.util.Random;
public class ApiGruas {
// Número de gruas en el sistema
public final int MAX_GRUAS;
// Peso mínimo que cargará una grua
public final int MIN_P_GRUA;
// Peso mínimo que cargará una grua
public final int MAX_P_GRUA;
// Tiempo mínimo para la descarga
private final int TIEMPO_MIN_SOLTAR_MS;
// Tiempo máximo para la descarga
private final int TIEMPO_MAX_SOLTAR_MS;
// El generador números aleatorios, contenedor y cargas van a ser
// usados simultáneamente
private Semaphore mutex = new Semaphore(1);
// Generador de números aleatorios
private Random random = new Random(0);
// API del contenedor
private ApiContenedor contenedor;
// Cargas de cada grua
private int[] cargas;
// Clase sin objetos
public ApiGruas(ApiContenedor contenedor,
int max_gruas,
int min_p_grua,
int max_p_grua) {
this.contenedor = contenedor;
MAX_GRUAS = max_gruas;
MIN_P_GRUA = min_p_grua;
MAX_P_GRUA = max_p_grua;
TIEMPO_MIN_SOLTAR_MS = MIN_P_GRUA / 10;
TIEMPO_MAX_SOLTAR_MS = MAX_P_GRUA / 10;
cargas = new int[MAX_GRUAS];
for (int idGrua = 0; idGrua < MAX_GRUAS; idGrua++) {
cargas[idGrua] = 0;
}
}
public int recoger(int idGrua) {
mutex.await();
int carga = MIN_P_GRUA + random.nextInt(MAX_P_GRUA - MIN_P_GRUA);
cargas[idGrua] = carga;
mutex.signal();
try {
Thread.sleep(2 * carga);
} catch (InterruptedException x) {}
return carga;
}
public void soltar(int idGrua) {
try {
mutex.await();
int t = random.nextInt(TIEMPO_MAX_SOLTAR_MS - TIEMPO_MIN_SOLTAR_MS);
contenedor.incrementar(cargas[idGrua]);
cargas[idGrua] = 0;
mutex.signal();
Thread.sleep(TIEMPO_MIN_SOLTAR_MS + t);
} catch (InterruptedException x) {}
}
}