我写了一个测试代码试了试,感觉这个semaphore控制并发量并不是绝对的给定量,比如我给semaphore的并发量是100,但是实际测试的代码并发量超过了100达到了110多,所以这个semaphore应该只能保证一个并发控制的范围而不能绝对保证不超过这个并发量是吧?
public class SemaPhoreTest {
private volatile int count=0;
private final int maxNumber=100;
public static void main(String[] args) {
SemaPhoreTest test=new SemaPhoreTest();
test.test();
}
public void test(){
ExecutorService service=Executors.newCachedThreadPool();
final int threadTotal=1000;
final Semaphore phore=new Semaphore(maxNumber);
for(int i=0;i<threadTotal;i++){
service.execute(new Runnable() {
public void run() {
try {
phore.acquire();
int temp= ++count;
doTask(0);
--count;
phore.release();
if(temp==maxNumber){
System.out.println("concurrent thread is full with value"+temp);
}else if(temp>maxNumber){
System.out.println("concurrent thread is over with value"+temp);
}else{
//System.err.println("concurrent thread is less");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
public void doTask(int num) throws InterruptedException{
Thread.sleep((int)((Math.random()*20)));
}