forked from learning-zone/java-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSemaphoreMethod.java
More file actions
79 lines (62 loc) · 1.77 KB
/
SemaphoreMethod.java
File metadata and controls
79 lines (62 loc) · 1.77 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
75
76
77
78
79
package multithreading;
import java.util.concurrent.*;
class Shared {
static int count = 0 ;
}
public class SemaphoreMethod extends Thread {
Semaphore sem;
String threadName;
public SemaphoreMethod(Semaphore sem, String threadName) {
super(threadName);
this.sem = sem;
this.threadName = threadName;
}
@Override
public void run() {
// run by thread A
if(this.getName().equals("A")) {
System.out.println("Starting " + threadName);
try {
System.out.println(threadName + " is waiting for a permit.");
// acquiring the lock
sem.acquire();
System.out.println(threadName + " gets a permit.");
for(int i = 0; i < 5; i++) {
Shared.count++;
System.out.println(threadName + ": " + Shared.count);
Thread.sleep(100);
}
} catch (Exception e) {
System.out.println("Exception: "+e);
}
System.out.println(threadName + " releases the permit.");
sem.release();
} else { // run by thread B
System.out.println("String " + threadName);
try {
System.out.println(threadName + " is waiting for a permit");
sem.acquire();
System.out.println(threadName + " gets a permit");
for(int i = 0; i < 5; i++) {
Shared.count--;
System.out.println(threadName + ": " + Shared.count);
Thread.sleep(100);
}
} catch (Exception e) {
System.out.println("Exception: " +e);
}
}
}
public static void main(String[] args) throws InterruptedException {
Semaphore sem = new Semaphore(1);
SemaphoreMethod mt1 = new SemaphoreMethod(sem, "A");
SemaphoreMethod mt2 = new SemaphoreMethod(sem, "B");
// stating threads A and B
mt1.start();
mt2.start();
// waiting for threads A and B
mt1.join();
mt2.join();
System.out.println("Count: " + Shared.count);
}
}