---
title: "信号量使用案例"
author: "zhanjun"
date: "2013-03-19T10:47:16Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-03-19T10:47:16Z"
id: 1831659
url: "https://zhanjun.iteye.com/blog/1831659"
---

信号量使用案例：

 

```
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class MySemaphore extends Thread {
Semaphore position;
private int id;
public MySemaphore(int i,Semaphore s){
    this.id=i;
    this.position=s;
}

public void run(){
    try{
    	if(position.getQueueLength()>30){
    		//如果拍排队人数超过30人     	
    		System.out.println("顾客["+this.id+"]，由于排队人数"+position.getQueueLength()+"太长，请换个厕所");
    		return;
    	}
     if(position.availablePermits()>0){
      System.out.println("顾客["+this.id+"]进入厕所，有空位");
     }
     else{
      System.out.println("顾客["+this.id+"]进入厕所，没空位，排队");
     }     
     position.acquire();
     System.out.println("顾客["+this.id+"]获得坑位");
     Thread.sleep((int)(Math.random()*1000));
     System.out.println("顾客["+this.id+"]使用完毕");
     position.release();
    }
    catch(Exception e){
     e.printStackTrace();
    }
}
public static void main(String args[]){
  ExecutorService list=Executors.newCachedThreadPool();
    Semaphore position=new Semaphore(5);//信号量是5，时间片内最多只有5个顾客上厕所
    for(int i=0;i<100;i++){
     list.submit(new MySemaphore(i+1,position));
    }
    list.shutdown();
    position.acquireUninterruptibly(2);
    System.out.println("使用完毕，需要清扫了");
    position.release(2);
}
}
```