Semaphore semaphore, in multi-threaded applications, the number of operations for controlling the simultaneous access to a particular resource or a specified number of operations performed simultaneously, and may also be used to implement a resource pool limit or boundary is applied to the container. simply put, Semaphore is synchronized in the enhanced version, you can control the number of concurrent threads.
A method to control the number of concurrent access
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(); } } }
.