Home > Java > javaTutorial > body text

What is the role of Semaphore in Java function concurrency and multi-threading?

WBOY
Release: 2024-04-27 12:18:01
Original
949 people have browsed it

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.

What is the role of Semaphore in Java function concurrency and multi-threading?

Concurrency of Java functions and the role of Semaphore in multi-threading

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.

Principle of action

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.

Practical Case

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();
        }
    }
}
Copy after login

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.

Conclusion

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!