- 1、本文档共28页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
多线程停车位实例
本文将介绍用来控制资源同时访问个数的Semaphore工具类, 然后采用Semaphore给出一个泊车的实例,最后给出Semaphore和CountDownLatch的几点比较. 1. Semaphore工具类介绍
Java代码 ?
/**?
?*?A?counting?semaphore.??Conceptually,?a?semaphore?maintains?a?set?of?
?*?permits.??Each?{@link?#acquire}?blocks?if?necessary?until?a?permit?is?
?*?available,?and?then?takes?it.??Each?{@link?#release}?adds?a?permit,?
?*?potentially?releasing?a?blocking?acquirer.?
?*?However,?no?actual?permit?objects?are?used;?the?ttSemaphore/tt?just?
?*?keeps?a?count?of?the?number?available?and?acts?accordingly.?
?*?
?*?pSemaphores?are?often?used?to?restrict?the?number?of?threads?than?can?
?*?access?some?(physical?or?logical)?resource.?
?*/??
从Semaphore的注释中可以看出如下几点: 1.从概念上讲,信号量维护了一个许可集。如有必要,在许可可用前会阻塞每一个 acquire(),然后再获取该许可。每个 release() 添加一个许可,从而可能释放一个正在阻塞的获取者。 2. Semaphore并不使用实际的许可对象,Semaphore 只对可用许可进行计数,并采取相应的行动。 3.Semaphore 通常用于限制可以访问某些资源(物理或逻辑的)的线程数目。 Semaphore中定义了一个内部类Sync,该类继承AbstractQueuedSynchronizer。 从代码中可以看出,Semaphore的方法基本上都调用了Sync的方法来实现。Smaphore还提供了公平和非公平的两种方式. Semaphore工具类相关的类图以及详细代码如下:
Java代码 ?
/*?
?*?@(#)Semaphore.java???1.8?04/07/12?
?*?
?*?Copyright?2004?Sun?Microsystems,?Inc.?All?rights?reserved.?
?*?SUN?PROPRIETARY/CONFIDENTIAL.?Use?is?subject?to?license?terms.?
?*/??
??
package?java.util.concurrent;??
import?java.util.*;??
import?java.util.concurrent.locks.*;??
import?java.util.concurrent.atomic.*;??
??
/**?
?*?A?counting?semaphore.??Conceptually,?a?semaphore?maintains?a?set?of?
?*?permits.??Each?{@link?#acquire}?blocks?if?necessary?until?a?permit?is?
?*?available,?and?then?takes?it.??Each?{@link?#release}?adds?a?permit,?
?*?potentially?releasing?a?blocking?acquirer.?
?*?However,?no?actual?permit?objects?are?used;?the?ttSemaphore/tt?just?
?*?keeps?a?count?of?the?number?available?and?acts?accordingly.?
?*?
?*?pSemaphores?are?often?used?to?restrict?the?number?of?threads?than?can?
?*?access?some?(physical?or?logical)?resource.?For?example,?here?is?
?*?a?class?that?uses?a?semaphore?to?control?access?to?a?pool?of?items:?
?*?pre?
?*
文档评论(0)