`

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

阅读更多

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

主要方法

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

 

例子

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

public class SemaphoreDemo {
	final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public static void main(String[] args) {
		Semaphore sem=new Semaphore(2);
		PC[]resources={new PC("PC-I"),new PC("PC-II")};
 		 
		for(int i=1;i<=5;i++){
			Player player=new Player("Player "+i,sem,resources);
            player.start();
		}
	}
    
	static class Player extends Thread{
		Semaphore sem;
		PC[]pcs;
		String playerName;
		public Player(String playerName,Semaphore sem,PC[]pcs){
			this.sem=sem;
			this.pcs=pcs;
			this.playerName=playerName;
		}
		public void run(){
			PC pc=getPC();//获取pc
			play(pc);//玩
			giveBackPC(pc);//归还pc
		}
		private void play(PC pc){
			if(pc==null)
				return;
			try {
				System.out.println(playerName+" play game with "+pc.getPcName()+" start at time "+sdf.format(new Date()));
				Thread.sleep(1000);
				System.out.println(playerName+" play game with "+pc.getPcName()+" over at time "+sdf.format(new Date()));

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		private PC getPC(){
			try {
				sem.acquire();
			} catch (InterruptedException e) {
				e.printStackTrace();
				return null;
			}
			for(PC pc:pcs){
				if(!pc.isOccupied()){
					pc.setOccupied(true);
					return pc;
				}
			}
			return null;
		}
        private void giveBackPC(PC pc){
			if(pc!=null)
				pc.setOccupied(false);
			sem.release();
		}
	}
	
	static class PC{
		private String pcName;
		private boolean occupied=false;
		PC(String pcName){
			this.pcName=pcName;
			
		}
		 
		public String getPcName() {
			return pcName;
		}

		public void setPcName(String pcName) {
			this.pcName = pcName;
		}

		public synchronized boolean isOccupied() {
			return occupied;
		}
		public synchronized void setOccupied(boolean occupied) {
			this.occupied = occupied;
		}
		 
	}
}

 

 

输出

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

1
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics