Share on Google+Share on Google+

Divya Khajuria
Please can I get the code for solution of producer consumer problem using semaphores?
1 Answer(s)      5 years and 8 months ago
Posted in : Java Beginners

Please can I get the code for solution of producer consumer problem using semaphores?

Ads

View Answers

August 19, 2011 at 4:11 PM


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);
    }
}









Related Tutorials/Questions & Answers:
Advertisements
Tutorials   
Java Spring Hibernate Struts Training What does core Java include? java What are some way to learn Java quickly? Is it required to learn Java before learning Java Script? Is it necessary to learn java script before learning PHP? Are HTML5 and Java Script boosts Java career? Is Java object oriented? Fingerprint application with Java Uninstall Oracle Virtual Box JSON to HashMap Free Java online Training I want example of Control Statement in Java ANSI Color Codes with Python Create a Program that Calculates Input What is difference between JDK,JRE and JVM? How to see ubuntu version on server? How to get Page Source in Selenium (WebDriver) using Java? The path to the driver executable must be set by the webdriver.gecko.driver system property parse data from a link in java Java Program Qns using BlueJ How to fix HAX Kernel Module Is Not Installed error? Installing Audacity Looking for code Logic to check track changes & Coments in MSWord, MSWordx, MSExcel, MSExcelx is ON/OFF Installing JDK on Mac SAX Parser exception ERROR 601 (42P00): Syntax error. Encountered Thread java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory How to install Ubuntu 16.04 LTS? HttpServletRequest cannot be resolved to a type in eclipse - Solved Unhandled event loop exception GC overhead limit exceeded Spring Data jpa with apache phoenix Caused by: java.lang.IllegalArgumentException: Not a host:port pair: PBUF o.a.h.h.z.RecoverableZooKeeper - Possibly transient ZooKeeper, quorum= com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager class not found com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager not found How to download and install Java 8 on Windows? How to uninstall JDK 7? How to install gtk-doc-tools package in Ubuntu? How to install Oracle JDK 8 on Ubuntu? ejabberd_ctl.beam not found - Solved How to convert date to UTC format in Java? How to install autoconf, automake and libtool in Ubuntu 15.10? How to convert current date to mm dd yyyy format in Java? How to convert current date to dd mm yyyy format in Java? How to stop window closing in "internalFrameClosing" event. How to find list of all index in Neo4j? neo4j-server.properties file location SASLError using PLAIN: not-authorized how to convert war file into .exe file using java code

Ads

 
Advertisement null

Ads