Thread Java 30 days- day 5(Semaphore)

paul chou
2 min readAug 2, 2023

I have already introduced how to write programs related to Java Threads. In the next few days, I will be covering some classes under the java.util.concurrent package. These classes can be helpful in managing Threads.

Today, I will introduce the Semaphore class. The Semaphore class is mainly used to control the maximum number of times a Thread can be used. If the set limit of the Semaphore is exceeded, the Thread will wait for other threads to complete before it can enter. Semaphore is commonly used in the following scenarios:

  1. Resource Pool Management: When you have a pool of resources (such as database connections, network connections, etc.) and you want multiple threads to access these resources simultaneously, Semaphore can help you control resource allocation and release.
  2. Limiting Concurrency: Sometimes you may want to limit the number of threads concurrently executing certain tasks to avoid excessive concurrency that leads to resource wastage or performance degradation.
  3. Avoiding Resource Competition: When multiple threads access shared resources, using Semaphore can prevent resource competition and ensure thread safety.

When creating a Semaphore object, you need to specify the number of threads that are allowed to use it in the constructor. The program is as follows:


import java.util.concurrent.Semaphore;


public class Main {
private static final int MAX_AVAILABLE_RESOURCES = 3;
private static Semaphore semaphore = new Semaphore(MAX_AVAILABLE_RESOURCES);

public static void main(String[] args) throws Exception {

for (int i = 1; i <= 3; i++) {
Thread thread = new Thread(new ResourceUser(i));
thread.start();
}

}

static class ResourceUser implements Runnable {
private int userId;

public ResourceUser(int userId) {
this.userId = userId;
}

@Override
public void run() {


System.out.println("User " + userId + " is trying to access the resource.");
try {

System.out.println("User " + userId + " has acquired the resource.");
semaphore.acquire();
Thread.sleep(2000);
System.out.println("User " + userId + " is releasing the resource.");
semaphore.release();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}


}
}


}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response