-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSemaPhores.java
More file actions
89 lines (67 loc) · 2.84 KB
/
SemaPhores.java
File metadata and controls
89 lines (67 loc) · 2.84 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
80
81
82
83
84
85
86
87
88
89
/* 6.
Semaphores : 'permit-based' access
limited number of threads at a time (Lock- only one thread at a time)
used to managing limited resources in a concurrent environment
acquire() vs acquireUninterruptibly()
acquire() is interruptible. That means if a thread A is calling acquire() on a semaphore, and thread B interrupts threads A by calling interrupt(), then an InterruptedException will be thrown on thread A.
On the other hand acquireUninterruptibly() is not interruptible. That means if a thread A is calling acquireUninterruptibly() on a semaphore, and thread B interrupts threads A by calling interrupt(), then no InterruptedException will be thrown on thread A, just that thread A will have its interrupted status set after acquireUninterruptibly() returns.
*/
import java.util.*;
import java.util.concurrent.Semaphore;
public class SemaPhores {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Thread> threads = new ArrayList<>();
Semaphore sema = new Semaphore(3, true); // fair == true --> Queue
while (true) {
System.out.print("Enter n & get nth prime number : ");
int num = sc.nextInt();
if (num == 0) {
System.out.println("Waiting for all threads to finish...");
waitForThreads(threads);
System.out.println("Done! " + threads.size() + " primes calculated");
break;
}
Thread t = new Thread(() -> {
// sema.acquireUninterruptibly(); // ignores interruption
try {
sema.acquire();
calculatePrime(num);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
sema.release();
}
});
threads.add(t);
t.start();
try {
t.join(100); // waits at most 100 ms for thread to die else it will continue
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static void calculatePrime(int num) {
int numOfPrimeFound = 1;
int number = 2;
int i;
while (numOfPrimeFound < num) {
number++;
for (i = 2; i * i <= number && number % i != 0; i++)
;
if (i * i > number)
numOfPrimeFound++;
}
System.out.println(num + "th prime : " + number);
}
private static void waitForThreads(List<Thread> threads) {
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}