ITeye博客

Java并发编程: 使用Semaphore限制资源并发访问的线程数

iaspecwang · 2013-08-24 08:18 · java线程 · 企业架构 · Markdown

本文将介绍用来控制资源同时访问个数的Semaphore工具类, 然后采用Semaphore给出一个泊车的实例,最后给出Semaphore和CountDownLatch的几点比较. 

1. Semaphore工具类介绍 

Java代码  收藏代码

  1. /**
  2. * A counting semaphore.  Conceptually, a semaphore maintains a set of
  3. * permits.  Each {@link #acquire} blocks if necessary until a permit is
  4. * available, and then takes it.  Each {@link #release} adds a permit,
  5. * potentially releasing a blocking acquirer.
  6. * However, no actual permit objects are used; the <tt>Semaphore</tt> just
  7. * keeps a count of the number available and acts accordingly.
  8. *
  9. * <p>Semaphores are often used to restrict the number of threads than can
  10. * access some (physical or logical) resource.
  11. */

从Semaphore的注释中可以看出如下几点: 
1.从概念上讲,信号量维护了一个许可集。如有必要,在许可可用前会阻塞每一个 acquire(),然后再获取该许可。每个 release() 添加一个许可,从而可能释放一个正在阻塞的获取者。 
2. Semaphore并不使用实际的许可对象,Semaphore 只对可用许可进行计数,并采取相应的行动。 

3.Semaphore 通常用于限制可以访问某些资源(物理或逻辑的)的线程数目。 

Semaphore中定义了一个内部类Sync,该类继承AbstractQueuedSynchronizer。 
从代码中可以看出,Semaphore的方法基本上都调用了Sync的方法来实现。Smaphore还提供了公平和非公平的两种方式. 

Semaphore工具类相关的类图以及详细代码如下: 

Java代码  收藏代码

  1. /*
  2. * @(#)Semaphore.java   1.8 04/07/12
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util.concurrent;
  8. import java.util.*;
  9. import java.util.concurrent.locks.*;
  10. import java.util.concurrent.atomic.*;
  11. /**
  12. * A counting semaphore.  Conceptually, a semaphore maintains a set of
  13. * permits.  Each {@link #acquire} blocks if necessary until a permit is
  14. * available, and then takes it.  Each {@link #release} adds a permit,
  15. * potentially releasing a blocking acquirer.
  16. * However, no actual permit objects are used; the <tt>Semaphore</tt> just
  17. * keeps a count of the number available and acts accordingly.
  18. *
  19. * <p>Semaphores are often used to restrict the number of threads than can
  20. * access some (physical or logical) resource. For example, here is
  21. * a class that uses a semaphore to control access to a pool of items:
  22. * <pre>
  23. * class Pool {
  24. *   private static final MAX_AVAILABLE = 100;
  25. *   private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
  26. *
  27. *   public Object getItem() throws InterruptedException {
  28. *     available.acquire();
  29. *     return getNextAvailableItem();
  30. *   }
  31. *
  32. *   public void putItem(Object x) {
  33. *     if (markAsUnused(x))
  34. *       available.release();
  35. *   }
  36. *
  37. *   // Not a particularly efficient data structure; just for demo
  38. *
  39. *   protected Object[] items = ... whatever kinds of items being managed
  40. *   protected boolean[] used = new boolean[MAX_AVAILABLE];
  41. *
  42. *   protected synchronized Object getNextAvailableItem() {
  43. *     for (int i = 0; i < MAX_AVAILABLE; ++i) {
  44. *       if (!used[i]) {
  45. *          used[i] = true;
  46. *          return items[i];
  47. *       }
  48. *     }
  49. *     return null; // not reached
  50. *   }
  51. *
  52. *   protected synchronized boolean markAsUnused(Object item) {
  53. *     for (int i = 0; i < MAX_AVAILABLE; ++i) {
  54. *       if (item == items[i]) {
  55. *          if (used[i]) {
  56. *            used[i] = false;
  57. *            return true;
  58. *          } else
  59. *            return false;
  60. *       }
  61. *     }
  62. *     return false;
  63. *   }
  64. *
  65. * }
  66. * </pre>
  67. *
  68. * <p>Before obtaining an item each thread must acquire a permit from
  69. * the semaphore, guaranteeing that an item is available for use. When
  70. * the thread has finished with the item it is returned back to the
  71. * pool and a permit is returned to the semaphore, allowing another
  72. * thread to acquire that item.  Note that no synchronization lock is
  73. * held when {@link #acquire} is called as that would prevent an item
  74. * from being returned to the pool.  The semaphore encapsulates the
  75. * synchronization needed to restrict access to the pool, separately
  76. * from any synchronization needed to maintain the consistency of the
  77. * pool itself.
  78. *
  79. * <p>A semaphore initialized to one, and which is used such that it
  80. * only has at most one permit available, can serve as a mutual
  81. * exclusion lock.  This is more commonly known as a [i]binary
  82. * semaphore[/i], because it only has two states: one permit
  83. * available, or zero permits available.  When used in this way, the
  84. * binary semaphore has the property (unlike many {@link Lock}
  85. * implementations), that the "lock" can be released by a
  86. * thread other than the owner (as semaphores have no notion of
  87. * ownership).  This can be useful in some specialized contexts, such
  88. * as deadlock recovery.
  89. *
  90. * <p> The constructor for this class optionally accepts a
  91. * [i]fairness[/i] parameter. When set false, this class makes no
  92. * guarantees about the order in which threads acquire permits. In
  93. * particular, [i]barging[/i] is permitted, that is, a thread
  94. * invoking {@link #acquire} can be allocated a permit ahead of a
  95. * thread that has been waiting - logically the new thread places itself at
  96. * the head of the queue of waiting threads. When fairness is set true, the
  97. * semaphore guarantees that threads invoking any of the {@link
  98. * #acquire() acquire} methods are selected to obtain permits in the order in
  99. * which their invocation of those methods was processed
  100. * (first-in-first-out; FIFO). Note that FIFO ordering necessarily
  101. * applies to specific internal points of execution within these
  102. * methods.  So, it is possible for one thread to invoke
  103. * <tt>acquire</tt> before another, but reach the ordering point after
  104. * the other, and similarly upon return from the method.
  105. * Also note that the untimed {@link #tryAcquire() tryAcquire} methods do not
  106. * honor the fairness setting, but will take any permits that are
  107. * available.
  108. *
  109. * <p>Generally, semaphores used to control resource access should be
  110. * initialized as fair, to ensure that no thread is starved out from
  111. * accessing a resource. When using semaphores for other kinds of
  112. * synchronization control, the throughput advantages of non-fair
  113. * ordering often outweigh fairness considerations.
  114. *
  115. * <p>This class also provides convenience methods to {@link
  116. * #acquire(int) acquire} and {@link #release(int) release} multiple
  117. * permits at a time.  Beware of the increased risk of indefinite
  118. * postponement when these methods are used without fairness set true.
  119. *
  120. * @since 1.5
  121. * @author Doug Lea
  122. *
  123. */
  124. public class Semaphore implements java.io.Serializable {
  125. private static final long serialVersionUID = -3222578661600680210L;
  126. /** All mechanics via AbstractQueuedSynchronizer subclass */
  127. private final Sync sync;
  128. /**
  129. * Synchronization implementation for semaphore.  Uses AQS state
  130. * to represent permits. Subclassed into fair and nonfair
  131. * versions.
  132. */
  133. abstract static class Sync extends AbstractQueuedSynchronizer {
  134. Sync(int permits) {
  135. setState(permits);
  136. }
  137. final int getPermits() {
  138. return getState();
  139. }
  140. final int nonfairTryAcquireShared(int acquires) {
  141. for (;;) {
  142. int available = getState();
  143. int remaining = available - acquires;
  144. if (remaining < 0 ||
  145. compareAndSetState(available, remaining))
  146. return remaining;
  147. }
  148. }
  149. protected final boolean tryReleaseShared(int releases) {
  150. for (;;) {
  151. int p = getState();
  152. if (compareAndSetState(p, p + releases))
  153. return true;
  154. }
  155. }
  156. final void reducePermits(int reductions) {
  157. for (;;) {
  158. int current = getState();
  159. int next = current - reductions;
  160. if (compareAndSetState(current, next))
  161. return;
  162. }
  163. }
  164. final int drainPermits() {
  165. for (;;) {
  166. int current = getState();
  167. if (current == 0 || compareAndSetState(current, 0))
  168. return current;
  169. }
  170. }
  171. }
  172. /**
  173. * NonFair version
  174. */
  175. final static class NonfairSync extends Sync {
  176. NonfairSync(int permits) {
  177. super(permits);
  178. }
  179. protected int tryAcquireShared(int acquires) {
  180. return nonfairTryAcquireShared(acquires);
  181. }
  182. }
  183. /**
  184. * Fair version
  185. */
  186. final static class FairSync extends Sync {
  187. FairSync(int permits) {
  188. super(permits);
  189. }
  190. protected int tryAcquireShared(int acquires) {
  191. Thread current = Thread.currentThread();
  192. for (;;) {
  193. Thread first = getFirstQueuedThread();
  194. if (first != null && first != current)
  195. return -1;
  196. int available = getState();
  197. int remaining = available - acquires;
  198. if (remaining < 0 ||
  199. compareAndSetState(available, remaining))
  200. return remaining;
  201. }
  202. }
  203. }
  204. /**
  205. * Creates a <tt>Semaphore</tt> with the given number of
  206. * permits and nonfair fairness setting.
  207. * @param permits the initial number of permits available. This
  208. * value may be negative, in which case releases must
  209. * occur before any acquires will be granted.
  210. */
  211. public Semaphore(int permits) {
  212. sync = new NonfairSync(permits);
  213. }
  214. /**
  215. * Creates a <tt>Semaphore</tt> with the given number of
  216. * permits and the given fairness setting.
  217. * @param permits the initial number of permits available. This
  218. * value may be negative, in which case releases must
  219. * occur before any acquires will be granted.
  220. * @param fair true if this semaphore will guarantee first-in
  221. * first-out granting of permits under contention, else false.
  222. */
  223. public Semaphore(int permits, boolean fair) {
  224. sync = (fair)? new FairSync(permits) : new NonfairSync(permits);
  225. }
  226. /**
  227. * Acquires a permit from this semaphore, blocking until one is
  228. * available, or the thread is {@link Thread#interrupt interrupted}.
  229. *
  230. * <p>Acquires a permit, if one is available and returns immediately,
  231. * reducing the number of available permits by one.
  232. * <p>If no permit is available then the current thread becomes
  233. * disabled for thread scheduling purposes and lies dormant until
  234. * one of two things happens:
  235. * [list]
  236. * <li>Some other thread invokes the {@link #release} method for this
  237. * semaphore and the current thread is next to be assigned a permit; or
  238. * <li>Some other thread {@link Thread#interrupt interrupts} the current
  239. * thread.
  240. * [/list]
  241. *
  242. * <p>If the current thread:
  243. * [list]
  244. * <li>has its interrupted status set on entry to this method; or
  245. * <li>is {@link Thread#interrupt interrupted} while waiting
  246. * for a permit,
  247. * [/list]
  248. * then {@link InterruptedException} is thrown and the current thread's
  249. * interrupted status is cleared.
  250. *
  251. * @throws InterruptedException if the current thread is interrupted
  252. *
  253. * @see Thread#interrupt
  254. */
  255. public void acquire() throws InterruptedException {
  256. sync.acquireSharedInterruptibly(1);
  257. }
  258. /**
  259. * Acquires a permit from this semaphore, blocking until one is
  260. * available.
  261. *
  262. * <p>Acquires a permit, if one is available and returns immediately,
  263. * reducing the number of available permits by one.
  264. * <p>If no permit is available then the current thread becomes
  265. * disabled for thread scheduling purposes and lies dormant until
  266. * some other thread invokes the {@link #release} method for this
  267. * semaphore and the current thread is next to be assigned a permit.
  268. *
  269. * <p>If the current thread
  270. * is {@link Thread#interrupt interrupted} while waiting
  271. * for a permit then it will continue to wait, but the time at which
  272. * the thread is assigned a permit may change compared to the time it
  273. * would have received the permit had no interruption occurred. When the
  274. * thread does return from this method its interrupt status will be set.
  275. *
  276. */
  277. public void acquireUninterruptibly() {
  278. sync.acquireShared(1);
  279. }
  280. /**
  281. * Acquires a permit from this semaphore, only if one is available at the
  282. * time of invocation.
  283. * <p>Acquires a permit, if one is available and returns immediately,
  284. * with the value <tt>true</tt>,
  285. * reducing the number of available permits by one.
  286. *
  287. * <p>If no permit is available then this method will return
  288. * immediately with the value <tt>false</tt>.
  289. *
  290. * <p>Even when this semaphore has been set to use a
  291. * fair ordering policy, a call to <tt>tryAcquire()</tt> [i]will[/i]
  292. * immediately acquire a permit if one is available, whether or not
  293. * other threads are currently waiting.
  294. * This "barging" behavior can be useful in certain
  295. * circumstances, even though it breaks fairness. If you want to honor
  296. * the fairness setting, then use
  297. * {@link #tryAcquire(long, TimeUnit) tryAcquire(0, TimeUnit.SECONDS) }
  298. * which is almost equivalent (it also detects interruption).
  299. *
  300. * @return <tt>true</tt> if a permit was acquired and <tt>false</tt>
  301. * otherwise.
  302. */
  303. public boolean tryAcquire() {
  304. return sync.nonfairTryAcquireShared(1) >= 0;
  305. }
  306. /**
  307. * Acquires a permit from this semaphore, if one becomes available
  308. * within the given waiting time and the
  309. * current thread has not been {@link Thread#interrupt interrupted}.
  310. * <p>Acquires a permit, if one is available and returns immediately,
  311. * with the value <tt>true</tt>,
  312. * reducing the number of available permits by one.
  313. * <p>If no permit is available then
  314. * the current thread becomes disabled for thread scheduling
  315. * purposes and lies dormant until one of three things happens:
  316. * [list]
  317. * <li>Some other thread invokes the {@link #release} method for this
  318. * semaphore and the current thread is next to be assigned a permit; or
  319. * <li>Some other thread {@link Thread#interrupt interrupts} the current
  320. * thread; or
  321. * <li>The specified waiting time elapses.
  322. * [/list]
  323. * <p>If a permit is acquired then the value <tt>true</tt> is returned.
  324. * <p>If the current thread:
  325. * [list]
  326. * <li>has its interrupted status set on entry to this method; or
  327. * <li>is {@link Thread#interrupt interrupted} while waiting to acquire
  328. * a permit,
  329. * [/list]
  330. * then {@link InterruptedException} is thrown and the current thread's
  331. * interrupted status is cleared.
  332. * <p>If the specified waiting time elapses then the value <tt>false</tt>
  333. * is returned.
  334. * If the time is less than or equal to zero, the method will not wait
  335. * at all.
  336. *
  337. * @param timeout the maximum time to wait for a permit
  338. * @param unit the time unit of the <tt>timeout</tt> argument.
  339. * @return <tt>true</tt> if a permit was acquired and <tt>false</tt>
  340. * if the waiting time elapsed before a permit was acquired.
  341. *
  342. * @throws InterruptedException if the current thread is interrupted
  343. *
  344. * @see Thread#interrupt
  345. *
  346. */
  347. public boolean tryAcquire(long timeout, TimeUnit unit)
  348. throws InterruptedException {
  349. return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
  350. }
  351. /**
  352. * Releases a permit, returning it to the semaphore.
  353. * <p>Releases a permit, increasing the number of available permits
  354. * by one.
  355. * If any threads are trying to acquire a permit, then one
  356. * is selected and given the permit that was just released.
  357. * That thread is (re)enabled for thread scheduling purposes.
  358. * <p>There is no requirement that a thread that releases a permit must
  359. * have acquired that permit by calling {@link #acquire}.
  360. * Correct usage of a semaphore is established by programming convention
  361. * in the application.
  362. */
  363. public void release() {
  364. sync.releaseShared(1);
  365. }
  366. /**
  367. * Acquires the given number of permits from this semaphore,
  368. * blocking until all are available,
  369. * or the thread is {@link Thread#interrupt interrupted}.
  370. *
  371. * <p>Acquires the given number of permits, if they are available,
  372. * and returns immediately,
  373. * reducing the number of available permits by the given amount.
  374. *
  375. * <p>If insufficient permits are available then the current thread becomes
  376. * disabled for thread scheduling purposes and lies dormant until
  377. * one of two things happens:
  378. * [list]
  379. * <li>Some other thread invokes one of the {@link #release() release}
  380. * methods for this semaphore, the current thread is next to be assigned
  381. * permits and the number of available permits satisfies this request; or
  382. * <li>Some other thread {@link Thread#interrupt interrupts} the current
  383. * thread.
  384. * [/list]
  385. *
  386. * <p>If the current thread:
  387. * [list]
  388. * <li>has its interrupted status set on entry to this method; or
  389. * <li>is {@link Thread#interrupt interrupted} while waiting
  390. * for a permit,
  391. * [/list]
  392. * then {@link InterruptedException} is thrown and the current thread's
  393. * interrupted status is cleared.
  394. * Any permits that were to be assigned to this thread are instead
  395. * assigned to other threads trying to acquire permits, as if
  396. * permits had been made available by a call to {@link #release()}.
  397. *
  398. * @param permits the number of permits to acquire
  399. *
  400. * @throws InterruptedException if the current thread is interrupted
  401. * @throws IllegalArgumentException if permits less than zero.
  402. *
  403. * @see Thread#interrupt
  404. */
  405. public void acquire(int permits) throws InterruptedException {
  406. if (permits < 0) throw new IllegalArgumentException();
  407. sync.acquireSharedInterruptibly(permits);
  408. }
  409. /**
  410. * Acquires the given number of permits from this semaphore,
  411. * blocking until all are available.
  412. *
  413. * <p>Acquires the given number of permits, if they are available,
  414. * and returns immediately,
  415. * reducing the number of available permits by the given amount.
  416. *
  417. * <p>If insufficient permits are available then the current thread becomes
  418. * disabled for thread scheduling purposes and lies dormant until
  419. * some other thread invokes one of the {@link #release() release}
  420. * methods for this semaphore, the current thread is next to be assigned
  421. * permits and the number of available permits satisfies this request.
  422. *
  423. * <p>If the current thread
  424. * is {@link Thread#interrupt interrupted} while waiting
  425. * for permits then it will continue to wait and its position in the
  426. * queue is not affected. When the
  427. * thread does return from this method its interrupt status will be set.
  428. *
  429. * @param permits the number of permits to acquire
  430. * @throws IllegalArgumentException if permits less than zero.
  431. *
  432. */
  433. public void acquireUninterruptibly(int permits) {
  434. if (permits < 0) throw new IllegalArgumentException();
  435. sync.acquireShared(permits);
  436. }
  437. /**
  438. * Acquires the given number of permits from this semaphore, only
  439. * if all are available at the time of invocation.
  440. *
  441. * <p>Acquires the given number of permits, if they are available, and
  442. * returns immediately, with the value <tt>true</tt>,
  443. * reducing the number of available permits by the given amount.
  444. *
  445. * <p>If insufficient permits are available then this method will return
  446. * immediately with the value <tt>false</tt> and the number of available
  447. * permits is unchanged.
  448. *
  449. * <p>Even when this semaphore has been set to use a fair ordering
  450. * policy, a call to <tt>tryAcquire</tt> [i]will[/i]
  451. * immediately acquire a permit if one is available, whether or
  452. * not other threads are currently waiting.  This
  453. * "barging" behavior can be useful in certain
  454. * circumstances, even though it breaks fairness. If you want to
  455. * honor the fairness setting, then use {@link #tryAcquire(int,
  456. * long, TimeUnit) tryAcquire(permits, 0, TimeUnit.SECONDS) }
  457. * which is almost equivalent (it also detects interruption).
  458. *
  459. * @param permits the number of permits to acquire
  460. *
  461. * @return <tt>true</tt> if the permits were acquired and <tt>false</tt>
  462. * otherwise.
  463. * @throws IllegalArgumentException if permits less than zero.
  464. */
  465. public boolean tryAcquire(int permits) {
  466. if (permits < 0) throw new IllegalArgumentException();
  467. return sync.nonfairTryAcquireShared(permits) >= 0;
  468. }
  469. /**
  470. * Acquires the given number of permits from this semaphore, if all
  471. * become available within the given waiting time and the
  472. * current thread has not been {@link Thread#interrupt interrupted}.
  473. * <p>Acquires the given number of permits, if they are available and
  474. * returns immediately, with the value <tt>true</tt>,
  475. * reducing the number of available permits by the given amount.
  476. * <p>If insufficient permits are available then
  477. * the current thread becomes disabled for thread scheduling
  478. * purposes and lies dormant until one of three things happens:
  479. * [list]
  480. * <li>Some other thread invokes one of the {@link #release() release}
  481. * methods for this semaphore, the current thread is next to be assigned
  482. * permits and the number of available permits satisfies this request; or
  483. * <li>Some other thread {@link Thread#interrupt interrupts} the current
  484. * thread; or
  485. * <li>The specified waiting time elapses.
  486. * [/list]
  487. * <p>If the permits are acquired then the value <tt>true</tt> is returned.
  488. * <p>If the current thread:
  489. * [list]
  490. * <li>has its interrupted status set on entry to this method; or
  491. * <li>is {@link Thread#interrupt interrupted} while waiting to acquire
  492. * the permits,
  493. * [/list]
  494. * then {@link InterruptedException} is thrown and the current thread's
  495. * interrupted status is cleared.
  496. * Any permits that were to be assigned to this thread, are instead
  497. * assigned to other threads trying to acquire permits, as if
  498. * the permits had been made available by a call to {@link #release()}.
  499. *
  500. * <p>If the specified waiting time elapses then the value <tt>false</tt>
  501. * is returned.
  502. * If the time is
  503. * less than or equal to zero, the method will not wait at all.
  504. * Any permits that were to be assigned to this thread, are instead
  505. * assigned to other threads trying to acquire permits, as if
  506. * the permits had been made available by a call to {@link #release()}.
  507. *
  508. * @param permits the number of permits to acquire
  509. * @param timeout the maximum time to wait for the permits
  510. * @param unit the time unit of the <tt>timeout</tt> argument.
  511. * @return <tt>true</tt> if all permits were acquired and <tt>false</tt>
  512. * if the waiting time elapsed before all permits were acquired.
  513. *
  514. * @throws InterruptedException if the current thread is interrupted
  515. * @throws IllegalArgumentException if permits less than zero.
  516. *
  517. * @see Thread#interrupt
  518. *
  519. */
  520. public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
  521. throws InterruptedException {
  522. if (permits < 0) throw new IllegalArgumentException();
  523. return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout));
  524. }
  525. /**
  526. * Releases the given number of permits, returning them to the semaphore.
  527. * <p>Releases the given number of permits, increasing the number of
  528. * available permits by that amount.
  529. * If any threads are trying to acquire permits, then one
  530. * is selected and given the permits that were just released.
  531. * If the number of available permits satisfies that thread's request
  532. * then that thread is (re)enabled for thread scheduling purposes;
  533. * otherwise the thread will wait until sufficient permits are available.
  534. * If there are still permits available
  535. * after this thread's request has been satisfied, then those permits
  536. * are assigned in turn to other threads trying to acquire permits.
  537. *
  538. * <p>There is no requirement that a thread that releases a permit must
  539. * have acquired that permit by calling {@link Semaphore#acquire acquire}.
  540. * Correct usage of a semaphore is established by programming convention
  541. * in the application.
  542. *
  543. * @param permits the number of permits to release
  544. * @throws IllegalArgumentException if permits less than zero.
  545. */
  546. public void release(int permits) {
  547. if (permits < 0) throw new IllegalArgumentException();
  548. sync.releaseShared(permits);
  549. }
  550. /**
  551. * Returns the current number of permits available in this semaphore.
  552. * <p>This method is typically used for debugging and testing purposes.
  553. * @return the number of permits available in this semaphore.
  554. */
  555. public int availablePermits() {
  556. return sync.getPermits();
  557. }
  558. /**
  559. * Acquire and return all permits that are immediately available.
  560. * @return the number of permits
  561. */
  562. public int drainPermits() {
  563. return sync.drainPermits();
  564. }
  565. /**
  566. * Shrinks the number of available permits by the indicated
  567. * reduction. This method can be useful in subclasses that use
  568. * semaphores to track resources that become unavailable. This
  569. * method differs from <tt>acquire</tt> in that it does not block
  570. * waiting for permits to become available.
  571. * @param reduction the number of permits to remove
  572. * @throws IllegalArgumentException if reduction is negative
  573. */
  574. protected void reducePermits(int reduction) {
  575. if (reduction < 0) throw new IllegalArgumentException();
  576. sync.reducePermits(reduction);
  577. }
  578. /**
  579. * Returns true if this semaphore has fairness set true.
  580. * @return true if this semaphore has fairness set true.
  581. */
  582. public boolean isFair() {
  583. return sync instanceof FairSync;
  584. }
  585. /**
  586. * Queries whether any threads are waiting to acquire. Note that
  587. * because cancellations may occur at any time, a <tt>true</tt>
  588. * return does not guarantee that any other thread will ever
  589. * acquire.  This method is designed primarily for use in
  590. * monitoring of the system state.
  591. *
  592. * @return true if there may be other threads waiting to acquire
  593. * the lock.
  594. */
  595. public final boolean hasQueuedThreads() {
  596. return sync.hasQueuedThreads();
  597. }
  598. /**
  599. * Returns an estimate of the number of threads waiting to
  600. * acquire.  The value is only an estimate because the number of
  601. * threads may change dynamically while this method traverses
  602. * internal data structures.  This method is designed for use in
  603. * monitoring of the system state, not for synchronization
  604. * control.
  605. * @return the estimated number of threads waiting for this lock
  606. */
  607. public final int getQueueLength() {
  608. return sync.getQueueLength();
  609. }
  610. /**
  611. * Returns a collection containing threads that may be waiting to
  612. * acquire.  Because the actual set of threads may change
  613. * dynamically while constructing this result, the returned
  614. * collection is only a best-effort estimate.  The elements of the
  615. * returned collection are in no particular order.  This method is
  616. * designed to facilitate construction of subclasses that provide
  617. * more extensive monitoring facilities.
  618. * @return the collection of threads
  619. */
  620. protected Collection<Thread> getQueuedThreads() {
  621. return sync.getQueuedThreads();
  622. }
  623. /**
  624. * Returns a string identifying this semaphore, as well as its state.
  625. * The state, in brackets, includes the String
  626. * "Permits =" followed by the number of permits.
  627. * @return a string identifying this semaphore, as well as its
  628. * state
  629. */
  630. public String toString() {
  631. return super.toString() + "[Permits = " + sync.getPermits() + "]";
  632. }
  633. }

2. Semaphore工具类的使用案例 

本文给出的一个示例模拟30辆车去泊车,而车位有10个的场景. 当车位满时,出来一辆车,才能有一辆车进入停车. 

Java代码  收藏代码

  1. package my.concurrent.semaphore;
  2. import java.util.concurrent.Semaphore;
  3. public class Car implements Runnable {
  4. private final Semaphore parkingSlot;
  5. private int carNo;
  6. /**
  7. * @param parkingSlot
  8. * @param carName
  9. */
  10. public Car(Semaphore parkingSlot, int carNo) {
  11. this.parkingSlot = parkingSlot;
  12. this.carNo = carNo;
  13. }
  14. public void run() {
  15. try {
  16. parkingSlot.acquire();
  17. parking();
  18. sleep(300);
  19. parkingSlot.release();
  20. leaving();
  21. } catch (InterruptedException e) {
  22. // TODO Auto-generated catch block
  23. e.printStackTrace();
  24. }
  25. }
  26. private void parking() {
  27. System.out.println(String.format("%d号车泊车", carNo));
  28. }
  29. private void leaving() {
  30. System.out.println(String.format("%d号车离开车位", carNo));
  31. }
  32. private static void sleep(long millis) {
  33. try {
  34. Thread.sleep(millis);
  35. } catch (InterruptedException e) {
  36. // TODO Auto-generated catch block
  37. e.printStackTrace();
  38. }
  39. }
  40. }

Java代码  收藏代码

  1. package my.concurrent.semaphore;
  2. import java.util.concurrent.ExecutorService;
  3. import java.util.concurrent.Executors;
  4. import java.util.concurrent.Semaphore;
  5. public class ParkingCars {
  6. private static final int NUMBER_OF_CARS = 30;
  7. private static final int NUMBER_OF_PARKING_SLOT = 10;
  8. public static void main(String[] args) {
  9. /*
  10. * 采用FIFO, 设置true
  11. */
  12. Semaphore parkingSlot = new Semaphore(NUMBER_OF_PARKING_SLOT, true);
  13. ExecutorService service = Executors.newCachedThreadPool();
  14. for (int carNo = 1; carNo <= NUMBER_OF_CARS; carNo++) {
  15. service.execute(new Car(parkingSlot, carNo));
  16. }
  17. sleep(3000);
  18. service.shutdown();
  19. /*
  20. * 输出还有几个可以用的资源数
  21. */
  22. System.out.println(parkingSlot.availablePermits() + " 个停车位可以用!");
  23. }
  24. private static void sleep(long millis) {
  25. try {
  26. Thread.sleep(millis);
  27. } catch (InterruptedException e) {
  28. // TODO Auto-generated catch block
  29. e.printStackTrace();
  30. }
  31. }
  32. }

一次运行的结果如下: 
1号车泊车 
4号车泊车 
9号车泊车 
2号车泊车 
8号车泊车 
10号车泊车 
3号车泊车 
12号车泊车 
14号车泊车 
6号车泊车 
2号车离开车位 
4号车离开车位 
6号车离开车位 
1号车离开车位 
9号车离开车位 
3号车离开车位 
5号车泊车 
8号车离开车位 
10号车离开车位 
11号车泊车 
7号车泊车 
12号车离开车位 
13号车泊车 
14号车离开车位 
16号车泊车 
17号车泊车 
20号车泊车 
19号车泊车 
18号车泊车 
15号车泊车 
5号车离开车位 
20号车离开车位 
18号车离开车位 
22号车泊车 
11号车离开车位 
7号车离开车位 
13号车离开车位 
15号车离开车位 
21号车泊车 
26号车泊车 
23号车泊车 
28号车泊车 
25号车泊车 
16号车离开车位 
27号车泊车 
17号车离开车位 
30号车泊车 
24号车泊车 
29号车泊车 
19号车离开车位 
25号车离开车位 
24号车离开车位 
22号车离开车位 
26号车离开车位 
28号车离开车位 
30号车离开车位 
21号车离开车位 
23号车离开车位 
27号车离开车位 
29号车离开车位 
10 个停车位可以用! 

3. Semaphore vs. CountDownLatch 

相同点:   
    两者都是用于线程同步的工具类,都通过定义了一个继承AbstractQueuedSynchronizer的内部类Sync来实现具体的功能. 

不同点: 
1.  Semaphore提供了公平和非公平两种策略, 而CountDownLatch则不具备. 
2.  CountDownLatch: 一个或者是一部分线程,等待另外一部线程都完成操作。 
     Semaphorr: 维护一个许可集.通常用于限制可以访问某些资源(物理或逻辑的)的线程数目. 

3. CountDownLatch中计数是不能被重置的。CountDownLatch适用于一次同步。当使用CountDownLatch时,任何线程允许多次调用countDown(). 那些调用了await()方法的线程将被阻塞,直到那些没有被阻塞线程调用countDown()使计数到达0为止 
。 
Semaphore允许线程获取许可, 未获得许可的线程需要等待.这样防止了在同一时间有太多的线程执行.Semaphore的值被获取到后是可以释放的,并不像CountDownLatch那样一直减到0。 

4. 使用CountDownLatch时,它关注的一个线程或者多个线程需要在其它在一组线程完成操作之后,在去做一些事情。比如:服务的启动等。使用Semaphore时,它关注的是某一个资源最多同时能被几个线程访问.

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。