How to use the Semaphore tool in Java for multi-threadi…
Semaphore is a crucial tool in Java for managing access to shared resources by multiple threads. It acts as a counter semaphore, controlling the number of threads accessing a resource at the same time.
Here are some common methods of semaphore:
- acquire(): Obtain a permit; if no permit is available, the thread will be blocked until one is available.
- release(): Releases a permit, allowing other threads to acquire the permit. If there are blocked threads waiting for the permit, it will select one thread to acquire the permit.
Here is an example code using Semaphore:
import java.util.concurrent.Semaphore;
public class SemaphoreExample {
public static void main(String[] args) {
// 创建Semaphore对象,指定许可的数量为3
Semaphore semaphore = new Semaphore(3);
// 创建10个线程
for (int i = 0; i < 10; i++) {
final int threadNum = i;
new Thread(() -> {
try {
// 获取许可
semaphore.acquire();
System.out.println("Thread " + threadNum + " is running");
Thread.sleep(1000);
System.out.println("Thread " + threadNum + " is finished");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 释放许可
semaphore.release();
}
}).start();
}
}
}
The code above creates a Semaphore object with 3 permits. It then creates 10 threads, each of which must acquire a permit before executing. If permits are unavailable, the threads will be blocked. After completing their task, they release the permit so that other threads can acquire it to continue executing.
When you run the code above, you will find that only a maximum of 3 threads are executing simultaneously, while the others will be blocked, waiting for the release of permission. This can effectively control access to shared resources.