Semaphore is a mechanism for controlling multi-threaded resource access in Java concurrent programming. It is implemented by creating a license. The license count is specified during initialization, indicating the number of protected resources that a thread can access at the same time. When a thread attempts to access a resource, it An attempt will be made to obtain a license, and if no license is available, the thread will be blocked until a license is available.
Semaphore is an important mechanism in Java concurrent programming, used in multi-threaded scenarios Control access to resources. It does this by creating licenses for the shared data structures that protect the resources.
Semaphore specifies a license count when initialized, which indicates the maximum number of threads that can access protected resources at the same time. When a thread attempts to access a resource, it attempts to obtain a license on the semaphore. If available, the license is granted and the thread can access the resource. If no license is available, the thread will be blocked until a license becomes available.
Suppose we have a shared resource, that is, a queue. Only 5 threads can access the queue simultaneously. We can use a Semaphore to ensure this:
import java.util.concurrent.Semaphore; import java.util.Queue; public class Example { private static final int MAX_ACCESS_COUNT = 5; private static Semaphore semaphore = new Semaphore(MAX_ACCESS_COUNT); private static Queue<Integer> queue = new ConcurrentLinkedQueue<>(); public static void main(String[] args) { for (int i = 0; i < 10; i++) { new Thread(() -> accessQueue()).start(); } } private static void accessQueue() { try { // 尝试获取一个许可证 semaphore.acquire(); // 访问队列 queue.add((int) (Math.random() * 100)); // 释放许可证 semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } } }
In this example, the semaphore is initialized with 5 licenses. This ensures that only a maximum of 5 threads can access the queue simultaneously. Other threads will be blocked until a license is available.
Semaphore is very useful in controlling concurrent access to shared resources. It helps prevent data races and inconsistencies by limiting the number of threads that can access a resource simultaneously.
The above is the detailed content of What is the role of Semaphore in Java function concurrency and multi-threading?. For more information, please follow other related articles on the PHP Chinese website!