Semaphore 信号量, 在多线程应用中, 用来控制同时访问某个特定资源的操作数量, 或者同时执行某个指定操作的数量, 还可以用来实现某种资源池限制, 或者对容器施加边界. 简单地说, Semaphore就是synchronized的加强版, 可以控制线程的并发数量.
控制对某一方法并发的访问数量
public class DemoSemaphore {
# 1表示同时只允许1个线程访问, 3则表示3个
private Semaphore semaphore = new Semaphore(3);
public void exec() {
try {
semaphore.acquire();
long threadId = Thread.currentThread().getId();
System.out.println(threadId + " acquired");
long rand = (long)(Math.random() * 1000);
Thread.sleep(rand);
System.out.println(threadId + " end");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
public static void main(String[] args) {
DemoSemaphore demo = new DemoSemaphore();
for (int i = 0; i < 30; i++) {
new Thread(demo::exec).start();
}
}
}
.
原文:https://www.cnblogs.com/milton/p/11296998.html