-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutex.java
49 lines (40 loc) · 1.42 KB
/
mutex.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
import java.util.concurrent.Semaphore;
// https://mkyong.com/java/java-thread-mutex-and-semaphore-example/
// Chapter 3.4 Multiplex -> TheLittleBookOfSemaphores
public class mutex {
static Semaphore mutex = new Semaphore(1);
volatile static int count = 1;
static class MyLockerThread extends Thread {
String name = "";
MyLockerThread(String name) {
this.name = name;
}
public void run() {
try {
while (true) {
System.out.println(name + " : solicitando bloqueio");
mutex.acquire();
System.out.println(name + " : com permissão");
try {
count = count + 1;
Thread.sleep(1000);
} finally {
System.out.println(name + " : liberando");
System.out.println("Count " + count);
mutex.release();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
System.out.println("Total de semaforos disponíveis : "
+ mutex.availablePermits());
MyLockerThread t1 = new MyLockerThread("A");
t1.start();
MyLockerThread t2 = new MyLockerThread("B");
t2.start();
}
}