Advertisement
Josif_tepe

Untitled

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