我写了一个测试代码试了试,这个semaphore应该只能保证一个并发控制的范围而不能绝对保证不超过这个并发量是吧?
来源:6-3 J.U.C之AQS-Semaphore
![](http://img1.sycdn.imooc.com/user/533e4ca50001117901990200-100-100.jpg)
过客1
2019-03-05
我写了一个测试代码试了试,感觉这个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)));
}
写回答
2回答
-
Jimin
2019-03-05
好的~
10 -
过客1
提问者
2019-03-05
抱歉自己的代码有问题,把int 类型的count改为AtomicInteger后就正确了。
00
相似问题
并发架构系统承载能力的问题
回答 1
课程几个地方理解不了
回答 1