Saturday, February 4, 2023

Producer Consumer problem implementation in Java using Lock:

 

Here is an example of a Producer Consumer problem implementation in Java using Lock:


import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ProducerConsumerExample { private static List<Integer> list = new ArrayList<>(); private static Lock lock = new ReentrantLock(); private static Condition notFull = lock.newCondition(); private static Condition notEmpty = lock.newCondition(); public static void main(String[] args) { Thread producerThread = new Thread(new Producer()); Thread consumerThread = new Thread(new Consumer()); producerThread.start(); consumerThread.start(); } static class Producer implements Runnable { @Override public void run() { for (int i = 1; i <= 10; i++) { try { lock.lock(); while (list.size() == 5) { System.out.println("Producer is waiting as the list is full"); notFull.await(); } list.add(i); System.out.println("Producer has added " + i + " to the list"); notEmpty.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } } static class Consumer implements Runnable { @Override public void run() { while (true) { try { lock.lock(); while (list.size() == 0) { System.out.println("Consumer is waiting as the list is empty"); notEmpty.await(); } int item = list.remove(0); System.out.println("Consumer has removed " + item + " from the list"); notFull.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } } }

In this example, a lock is used to synchronize the access to the shared list by the producer and consumer threads. The notFull condition is used to wait for the producer thread when the list is full, and the notEmpty condition is used to wait for the consumer thread when the list is empty.

No comments:

Post a Comment