-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSemaphore.java
More file actions
42 lines (37 loc) · 843 Bytes
/
JSemaphore.java
File metadata and controls
42 lines (37 loc) · 843 Bytes
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
/*
Class that implements Semaphore functionality for use in
threaded Java applications.
written by Shafik Amin, 4-16-2003
*/
public final class JSemaphore
{
/** Instance fields **/
private int state;
private long timeout;
/* Constructors */
public JSemaphore(int initial, long sectimeout)
{
state = initial < 0 ? 0 : initial;
timeout = sectimeout < 0 ? 0 : sectimeout*1000;
}
public JSemaphore()
{
this(0, 60*60);
}
/* V's the semaphore's state, never blocks */
public synchronized void V()
{
state++;
notifyAll();
}
/* P's the semaphore's state, blocks when it reaches zero */
public synchronized void P()
{
state--;
if (state <= 0) /* change back to while for normal functionality */
{
try { wait(timeout); }
catch (InterruptedException ie) { }
}
}
}