读书人

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

发布时间: 2012-12-19 14:13:15 作者: rapoo

对资源的许可访问 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

读书人网 >编程

热点推荐