Advertisement
Josif_tepe

Untitled

Mar 26th, 2022
808
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1.  
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.*;
  5. import java.util.concurrent.Semaphore;
  6. import java.util.concurrent.locks.Lock;
  7. import java.util.concurrent.locks.ReentrantLock;
  8.  
  9. public class Fabrika {
  10.     int max_capacity = 5;
  11.     List<String> products = new ArrayList<>();
  12.     static Semaphore main_semaphore = new Semaphore(1);
  13.     static Semaphore producer_semaphore = new Semaphore(    10);
  14.     static Semaphore consume_semaphore = new Semaphore(10);
  15.     public Fabrika(int capacity) {
  16.         max_capacity = capacity;
  17.     }
  18.     public void produce(String s) throws InterruptedException{
  19.         producer_semaphore.acquire();
  20.         main_semaphore.acquire();
  21.         while(products.size() == max_capacity) {
  22.             main_semaphore.release();
  23.             Thread.sleep(2000);
  24.             main_semaphore.acquire();
  25.         }
  26.         products.add(s);
  27.         System.out.println("Produced " + s);
  28.         main_semaphore.release();
  29.         consume_semaphore.release();
  30.  
  31.     }
  32.     public void consume() throws InterruptedException {
  33.         consume_semaphore.acquire();
  34.         main_semaphore.acquire();
  35.         while(products.size() == 0) {
  36.             main_semaphore.release();
  37.             Thread.sleep(2000);
  38.             main_semaphore.acquire();
  39.         }
  40.         String s = products.remove(0);
  41.         System.out.println("Consumed " + s);
  42.         main_semaphore.release();
  43.         producer_semaphore.release();
  44.     }
  45.  
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement