-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSemaphoreDemo.java
More file actions
84 lines (73 loc) · 1.95 KB
/
Copy pathSemaphoreDemo.java
File metadata and controls
84 lines (73 loc) · 1.95 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
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Semaphore;
public class SemaphoreDemo{
public static void main(String[] args){
final Pool pool = new Pool();
Runnable runnable = new Runnable(){
@Override
public void run(){
String threadName = Thread.currentThread().getName();
try{
while(true){
String item;
System.out.println(threadName + " acquiring " + (item = pool.getItem()));
Thread.sleep(200 + (int)(Math.random()*1000));
System.out.println(threadName + " putting back " + item);
pool.putItem(item);
}
}catch(InterruptedException ie){
System.out.println(threadName + " has been interrupted.");
}
}
};
ExecutorService[] executors = new ExecutorService[Pool.MAX_AVAILABLE + 5];
for(int i=0;i<executors.length; i++){
executors[i] = Executors.newSingleThreadExecutor();
executors[i].execute(runnable);
}
}
}
final class Pool{
public static final int MAX_AVAILABLE = 5;
private Semaphore availabeSemaphore = new Semaphore(MAX_AVAILABLE, true);
private String[] items;
private boolean[] used = new boolean[MAX_AVAILABLE];
Pool(){
items = new String[MAX_AVAILABLE];
for(int i=0; i<items.length;i++){
items[i] = "Item_" + i;
}
}
String getItem() throws InterruptedException{
availabeSemaphore.acquire();
return getNextAvailabeItem();
}
void putItem(String item){
if(markAsUsed(item)){
availabeSemaphore.release();
}
}
private synchronized String getNextAvailabeItem(){
for(int i=0; i<MAX_AVAILABLE; i++){
if(!used[i]){
used[i] = true;
return items[i];
}
}
return null; // Not reached in this logic implementation.
}
private synchronized boolean markAsUsed(String item){
for(int i=0; i<MAX_AVAILABLE; i++){
if( item == items[i]){
if(used[i]){
used[i] = false;
return true; // used before
}else{
return false;
}
}
}
return false;
}
}