-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSemaphoreDemo.java
More file actions
97 lines (72 loc) · 2.25 KB
/
SemaphoreDemo.java
File metadata and controls
97 lines (72 loc) · 2.25 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
90
91
92
93
94
95
96
97
package concurrency;
import java.util.concurrent.*;
import java.util.*;
/**
* RUN:
* javac concurrency/SemaphoreDemo.java && java concurrency.SemaphoreDemo
*
* OUTPUT:
*
*/
public class SemaphoreDemo {
final static int SIZE = 25;
public static void main(String[] args) throws Exception {
final Pool<Fat> pool = new Pool<Fat>(Fat.class, SIZE);
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < SIZE; i++) {
exec.execute(new CheckoutTask<Fat>(pool));
}
System.out.println("All CheckoutTasks created");
List<Fat> list = new ArrayList<Fat>();
for (int i = 0; i < SIZE; i++) {
Fat f = pool.checkOut();
System.out.print(i + " main() thread checked out ");
f.operation();
list.add(f);
}
Future<?> blocked = exec.submit(new Runnable() {
public void run() {
try {
// Semaphore blocking this checkOut() eexecution
pool.checkOut();
}
catch (InterruptedException e) {
System.out.println("checkOut() interrupted");
}
}
});
TimeUnit.SECONDS.sleep(2);
blocked.cancel(true); // return from blocking
System.out.println("Checking in objects in " + list);
for (Fat f : list) {
pool.checkIn(f);
}
for (Fat f : list) {
pool.checkIn(f); // this checkIn() ignored
}
exec.shutdown();
}
}
class CheckoutTask<T> implements Runnable {
private static int counter = 0;
private final int id = counter++;
private Pool<T> pool;
public CheckoutTask(Pool<T> pool) {
this.pool = pool;
}
public void run() {
try {
T item = pool.checkOut();
System.out.println(this + " checked out " + item);
TimeUnit.SECONDS.sleep(1);
System.out.println(this + " checked in " + item);
pool.checkIn(item);
}
catch (InterruptedException e) {
//
}
}
public String toString() {
return String.format("CheckoutTask %1$d ", id);
}
}