The Java Program: Semaphore.java
1 public class Semaphore {
2 protected Thread owner = null;
3 private int count = 0;
4
5 // block until lock is acquired
6 public synchronized void lock() {
7 while (!acquire()) {
8 try {
9 wait();
10 } catch (InterruptedException e) {
11 // Do nothing!
12 }
13 }
14 }
15
16 // Try to acquire the lock if possible
17 public synchronized boolean acquire() {
18 Thread current = Thread.currentThread(); // Who's calling?
19 if (owner == null) {
20 owner = current;
21 count = 1;
22 return true;
23 } else if (owner == current) {
24 count++; // Account for nested locks
25 return true;
26 } else {
27 return false;
28 }
29 }
30
31 public synchronized void unlock() {
32 Thread current = Thread.currentThread(); // Who's calling?
33 if (owner == current) {
34 count--;
35 if (count==0) {
36 owner = null;
37 notify();
38 }
39 }
40 }
41 }
42