java如何限制并发数(semaphore)
解决方法:
以下代码限制最多只有10个线程可能会同时执行semaphore.acquire();和 semaphore.release();之间的代码,保证了cpu资源不被耗尽
package service;
import java.util.concurrent.Semaphore;
public class Test{
private Semaphore semaphore = new Semaphore(10);
public void test() {
try {
semaphore.acquire();
//业务代码开始
int sleepValue = ((int) (Math.random() *10000));
Thread.sleep(sleepValue);
//业务代码结束
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}