首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

对资源的许可访问 Se地图hore用法小例

2012-12-19 
对资源的许可访问Semaphore用法小例Semaphore 通常用于限制可以访问某些资源(物理或逻辑的)的线程数目主要

对资源的许可访问 Semaphore用法小例

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

主要方法

???public Semaphore(int permits)? //构造一个指定许可数目的信号量
?? public void acquire()throws InterruptedException? // 获取信号量,没有则阻塞当前线程
???public void release()? //释放一个信号量
?? 另外还有相应的重载方法

?

例子

以下代码描述了这样一个应用,有2台pc,5个玩家,同一时刻只能有2个玩家使用pc(因为只有2台pc嘛),同一pc同一时刻只能归于一个玩家使用

?

?

输出

Player 1 play game with PC-I start at time 2011-04-14 12:59:49
Player 2 play game with PC-II start at time 2011-04-14 12:59:49
Player 2 play game with PC-II over at time 2011-04-14 12:59:50
Player 3 play game with PC-II start at time 2011-04-14 12:59:50
Player 1 play game with PC-I over at time 2011-04-14 12:59:50
Player 4 play game with PC-I start at time 2011-04-14 12:59:50
Player 4 play game with PC-I over at time 2011-04-14 12:59:51
Player 3 play game with PC-II over at time 2011-04-14 12:59:51
Player 5 play game with PC-I start at time 2011-04-14 12:59:51
Player 5 play game with PC-I over at time 2011-04-14 12:59:52

热点排行