Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package multithreading.semaphore.bounded;
- public class MyBoundedSemaphore {
- private final int maxAcquiresAtTime;
- private int currAcquiresCount = 0;
- public MyBoundedSemaphore(int maxAcquiresAtTime) {
- this.maxAcquiresAtTime = maxAcquiresAtTime;
- }
- public synchronized void acquire() throws InterruptedException {
- while(currAcquiresCount >= maxAcquiresAtTime) wait();
- currAcquiresCount++;
- }
- public synchronized void release() {
- notifyAll();
- currAcquiresCount--;
- }
- }
- package multithreading.semaphore.bounded;
- import java.util.Random;
- public class Api {
- private final MyBoundedSemaphore semaphore;
- public Api(MyBoundedSemaphore semaphore) {
- this.semaphore = semaphore;
- }
- private final Random random = new Random();
- public void makeRequest() throws InterruptedException {
- semaphore.acquire();
- System.out.println("Thread " + Thread.currentThread().getName() + " making a request");
- // Making a request...
- Thread.sleep(3000 + random.nextInt(10) * 500);
- System.out.println("Thread " + Thread.currentThread().getName() + " takes response from the server");
- semaphore.release();
- }
- }
- Client:
- package multithreading.semaphore.bounded;
- public class Client {
- public static void main(String[] args) throws InterruptedException {
- MyBoundedSemaphore semaphore = new MyBoundedSemaphore(2);
- Api api = new Api(semaphore);
- for (int i = 0; i < 4; i++) {
- new Thread(() -> {
- try {
- api.makeRequest();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }, "Thread " + i).start();
- }
- Thread.sleep(30000);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement