说明
Semaphore信号量作为一种流控手段
1.连接池的并发数
2.有界阻塞容器的容量等
3.acquire与release并没有强制的一对一关系,release一次就相当于新增一个许可
最大并发数
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaporeTest {
private static int threadTotal = 200;
private static int clientTotal = 5000;
private static int count = 0;
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
for (int i = 0; i < clientTotal; i++) {
executorService.execute(()->{
try {
semaphore.acquire();
add();
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
System.out.println(count);
}
private static void add() {
count++;
}
}