Producer, Consumer with ReentrantLock, Condition

By | August 27, 2021
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
public class PC {

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition added = lock.newCondition();
        Condition removed = lock.newCondition();
        int[] resource = new int[1];
        Consumer c1 = new Consumer(lock, added, removed, resource);
        Producer p1 = new Producer(lock, added, removed, resource);
        Producer p2 = new Producer(lock, added, removed, resource);
        new Thread(c1).start();
        new Thread(p1).start();
        new Thread(p2).start();
    }


    public static class Consumer implements Runnable {

        ReentrantLock lock;
        Condition added;
        Condition removed;
        int[] resource;

        public Consumer(ReentrantLock lock, Condition added, Condition removed, int[] resource) {
            this.lock = lock;
            this.resource = resource;
            this.added = added;
            this.removed = removed;
        }

        @SneakyThrows
        public void run() {
            while (true) {
                lock.lock();
                while (resource[0] <= 0) {
                    added.await();
                }
                resource[0]--;
                System.out.println(Thread.currentThread().getId() + " consume: " + resource[0]);
                removed.signalAll();
                lock.unlock();
                Thread.sleep(1000l);
            }
        }

    }

    public static class Producer implements Runnable {

        ReentrantLock lock;
        Condition added;
        Condition removed;
        int[] resource;
        int MAX = 5;

        public Producer(ReentrantLock lock, Condition added, Condition removed, int[] resource) {
            this.lock = lock;
            this.resource = resource;
            this.added = added;
            this.removed = removed;
        }

        @SneakyThrows
        public void run() {
            while (true) {
                lock.lock();
                while (resource[0] >= MAX) {
                    removed.await();
                }
                resource[0]++;
                System.out.println(Thread.currentThread().getId() + " produce: " + resource[0]);
                added.signalAll();
                lock.unlock();
                Thread.sleep(1000l);
            }
        }

    }

}