1 15 16 package EDU.oswego.cs.dl.util.concurrent; 17 18 88 89 90 public class Semaphore implements Sync { 91 92 protected long permits_; 93 94 100 public Semaphore(long initialPermits) { permits_ = initialPermits; } 101 102 103 104 public void acquire() throws InterruptedException { 105 if (Thread.interrupted()) throw new InterruptedException (); 106 synchronized(this) { 107 try { 108 while (permits_ <= 0) wait(); 109 --permits_; 110 } 111 catch (InterruptedException ex) { 112 notify(); 113 throw ex; 114 } 115 } 116 } 117 118 119 public boolean attempt(long msecs) throws InterruptedException { 120 if (Thread.interrupted()) throw new InterruptedException (); 121 122 synchronized(this) { 123 if (permits_ > 0) { 124 --permits_; 125 return true; 126 } 127 else if (msecs <= 0) 128 return false; 129 else { 130 try { 131 long startTime = System.currentTimeMillis(); 132 long waitTime = msecs; 133 134 for (;;) { 135 wait(waitTime); 136 if (permits_ > 0) { 137 --permits_; 138 return true; 139 } 140 else { 141 waitTime = msecs - (System.currentTimeMillis() - startTime); 142 if (waitTime <= 0) 143 return false; 144 } 145 } 146 } 147 catch(InterruptedException ex) { 148 notify(); 149 throw ex; 150 } 151 } 152 } 153 } 154 155 156 public synchronized void release() { 157 ++permits_; 158 notify(); 159 } 160 161 162 172 public synchronized void release(long n) { 173 if (n < 0) throw new IllegalArgumentException ("Negative argument"); 174 175 permits_ += n; 176 for (long i = 0; i < n; ++i) notify(); 177 } 178 179 184 public synchronized long permits() { 185 return permits_; 186 } 187 188 } 189 190 | Popular Tags |