-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathThreadProcessador.java
74 lines (62 loc) · 1.53 KB
/
ThreadProcessador.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
package view;
import java.util.concurrent.Semaphore;
public class ThreadProcessador {
private static Semaphore semaforo;
public static void main(String[] args) {
int numeroPermissoes = 1;
semaforo = new Semaphore(numeroPermissoes);
t1.start();
t2.start();
t3.start();
t4.start();
}
private static void processar(int idThread) {
try {
System.out.println("Thread #" + idThread + " processando");
int TempoDormir = (int) (Math.random() * 10000);
Thread.sleep(TempoDormir);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void entrarRegiaoNaoCritica(int idThread) {
System.out.println("Thread #" + idThread + " em região não crítica");
processar(idThread);
}
private static void entrarRegiaoCritica(int idThread) {
System.out.println("Thread #" + idThread + " entrando em região crítica");
processar(idThread);
System.out.println("Thread #" + idThread + " saindo da região crítica");
}
public static void processamento(int idThread) {
entrarRegiaoNaoCritica(idThread);
try {
semaforo.acquire();
entrarRegiaoCritica(idThread);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaforo.release();
}
}
static Thread t1 = new Thread() {
public void run() {
processamento(1);
}
};
static Thread t2 = new Thread() {
public void run() {
processamento(2);
}
};
static Thread t3 = new Thread() {
public void run() {
processamento(3);
}
};
static Thread t4 = new Thread() {
public void run() {
processamento(4);
}
};
}