Please can I get the code for solution of producer consumer problem using semaphores?
import java.util.*; class Semaphore{ private int value; private int waiting; private String message; public Semaphore(int val, String mess){ value = val; waiting = 0; message = mess; } public synchronized void down(){ if (value > 0){ value--; } else{ try{ waiting++; if (message != null) System.err.println(message); wait(); } catch (InterruptedException e){} } } public synchronized void up(){ if (waiting > 0){ notify(); waiting--; } else{ value++; } } } public class ProducerConsumerUsingSemaphores{ private Buffer b; private Semaphore full, empty, mutex; class Buffer{ private LinkedList buf; private int items; private int size; public Buffer(int n){ buf = new LinkedList(); items = 0; size = n; } public Object remove(){ Object result = buf.getFirst(); buf.remove(0); items--; return result; } public void add(Object item){ buf.add(item); items++; } } class Producer implements Runnable{ private int itemsToAdd; public Producer(int n){ itemsToAdd = n; } public void run(){ int i = 0; while (true){ try{ Thread.sleep((int)(Math.random() * 10) * 100); } catch (InterruptedException e){} empty.down(); mutex.down(); b.add(new Integer(i)); System.out.println("Producer added " + i); i++; mutex.up(); full.up(); } } } class Consumer extends Thread{ private int id; public Consumer(int i){ id = i; } public void run(){ while (true){ full.down(); mutex.down(); Integer item = (Integer)(b.remove()); System.out.println("Consumer " + id + " removed " + item); mutex.up(); empty.up(); try{ sleep((int)(Math.random() * 10) * 100); } catch (InterruptedException e){} } } } public ProducerConsumerUsingSemaphores(int items, int bufferSize, int consumers){ b = new Buffer(bufferSize); empty = new Semaphore(bufferSize, "Producer sleeping"); mutex = new Semaphore(1, null); full = new Semaphore(0, "Consumer sleeping"); for (int id = 0; id < consumers; id++){ Thread t = new Consumer(id); t.start(); } new Thread(new Producer(items)).start(); } public static void main(String[] args){ int bufferSize =2; int consumers = 1; new ProducerConsumerUsingSemaphores(0, bufferSize, consumers); } }
Ads