semaphore称为信号量,用来限制能同时访问共享资源的线程上限,应用场景为共享资源有多个,允许多个线程访问
semaphore示例
Semaphore semaphore = new Semaphore(3); // 限制上限为3
ExecutorService executorService = Executors.newFixedThreadPool(10);
ArrayList<Callable<String>> callables = new ArrayList<>();
for (int i = 0; i < 10; i++) {
int j = i;
callables.add(()->{
try {
semaphore.acquire(); // 获取信号量
Thread.sleep(1000);
System.out.println("成功获取semaphore");
}finally {
semaphore.release(); // 执行完毕释放信号量
System.out.println("成功释放取semaphore");
}
return "1 "+ j;
});
}
List<Future<String>> futures = executorService.invokeAll(callables);
futures.forEach(stringFuture -> {
try {
System.out.println(stringFuture.get());
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
});
semaphore应用
- 使用Semaphore限流,在访问高峰期时,让请求线程阻塞,高峰期过去再释放许可,当然它只适合限制单机线程数量,并且仅是限制线程数,而不是限制资源数(例如连接数,请对比Tomcat LimitLatch的实现)
- 用Semaphore实现简单连接池,对比『享元模式』下的实现(用wait notify),性能和可读性显然更好,注意下面的实现中线程数和数据库连接数是相等的