forked from learning-zone/java-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConcurrentSemaphore.java
More file actions
69 lines (53 loc) · 1.47 KB
/
ConcurrentSemaphore.java
File metadata and controls
69 lines (53 loc) · 1.47 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
package concurrent;
import java.util.concurrent.*;
public class ConcurrentSemaphore extends Thread {
Semaphore sem;
String threadName;
public ConcurrentSemaphore(Semaphore sem, String threadName) {
super(threadName);
this.sem = sem;
this.threadName = threadName;
}
@Override
public void run() {
System.out.println(threadName + " is waiting for a permit.");
try {
sem.acquire();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(threadName + " gets a permit.");
for(int i = 0; i < 2; i++) {
boolean b =sem.hasQueuedThreads();
if(b) {
System.out.println("Length of Queue: " + sem.getQueueLength());
}
try {
Thread.sleep(100);
} catch(Exception e) {
e.printStackTrace();
}
}
System.out.println(threadName + " releases the permit.");
sem.release();
}
public static void main(String[] args) {
Semaphore sem = new Semaphore(3, true);
System.out.println("Is fairness enabled: " + sem.isFair());
sem.tryAcquire(2);
System.out.println("Avaialable permits: " + sem.availablePermits());
System.out.println("Number of permits drain by Main thread: " +sem.drainPermits());
sem.release(1);
ConcurrentSemaphore mt1 = new ConcurrentSemaphore(sem, "A");
ConcurrentSemaphore mt2 = new ConcurrentSemaphore(sem, "B");
mt1.start();
mt2.start();
System.out.println(sem.toString());
try {
mt1.join();
mt2.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}