Sunday, March 29, 2020

Producer Consumer Occupation Amongst Facial Expression Together With Notify - Thread Example

Producer Consumer Problem is a classical concurrency occupation as well as inwards fact it is i of the concurrency blueprint pattern. In in conclusion article nosotros convey seen solving Producer Consumer occupation inwards Java using blocking Queue exactly i of my reader emailed me as well as requested code illustration as well as explanation of solving Producer Consumer occupation inwards Java  with wait as well as notify method every bit well, Since its oft asked every bit i of the meridian coding enquiry inwards Java. In this Java tutorial, I convey set the code illustration of await notify version of before producer consumer concurrency blueprint pattern. You tin run across this is much longer code amongst explicit treatment blocking weather condition similar when shared queue is total as well as when queue is empty. Since nosotros convey replaced BlockingQueue amongst Vector nosotros demand to implement blocking using wait as well as notify as well as that's why nosotros convey introduced produce(int i) as well as consume() method. If yous run across I convey kept consumer thread footling dull past times allowing it to slumber for fifty Milli instant to give an chance to producer to fill upwardly the queue, which helps to empathize that Producer thread is every bit good waiting when Queue is full.



Java computer program to solve Producer Consumer Problem inwards Java

Producer Consumer Problem is a classical concurrency occupation as well as inwards fact it is i of the  Producer Consumer Problem amongst Wait as well as Notify - Thread ExampleHere is consummate Java computer program to solve producer consumer occupation inwards Java programming language. In this computer program nosotros convey used await as well as notify method from java.lang.Object degree instead of using BlockingQueue for catamenia control.




import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Java computer program to solve Producer Consumer occupation using await as well as notify
 * method inwards Java. Producer Consumer is every bit good a pop concurrency blueprint pattern.
 *
 * @author Javin Paul
 */

public class ProducerConsumerSolution {

    public static void main(String args[]) {
        Vector sharedQueue = new Vector();
        int size = 4;
        Thread prodThread = new Thread(new Producer(sharedQueue, size), "Producer");
        Thread consThread = new Thread(new Consumer(sharedQueue, size), "Consumer");
        prodThread.start();
        consThread.start();
    }
}

class Producer implements Runnable {

    private final Vector sharedQueue;
    private final int SIZE;

    public Producer(Vector sharedQueue, int size) {
        this.sharedQueue = sharedQueue;
        this.SIZE = size;
    }

    @Override
    public void run() {
        for (int i = 0; i < 7; i++) {
            System.out.println("Produced: " + i);
            try {
                produce(i);
            } catch (InterruptedException ex) {
                Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    private void produce(int i) throws InterruptedException {

        //wait if queue is full
        while (sharedQueue.size() == SIZE) {
            synchronized (sharedQueue) {
                System.out.println("Queue is total " + Thread.currentThread().getName()
                                    + " is waiting , size: " + sharedQueue.size());

                sharedQueue.wait();
            }
        }

        //producing chemical gene as well as notify consumers
        synchronized (sharedQueue) {
            sharedQueue.add(i);
            sharedQueue.notifyAll();
        }
    }
}

class Consumer implements Runnable {

    private final Vector sharedQueue;
    private final int SIZE;

    public Consumer(Vector sharedQueue, int size) {
        this.sharedQueue = sharedQueue;
        this.SIZE = size;
    }

    @Override
    public void run() {
        while (true) {
            try {
                System.out.println("Consumed: " + consume());
                Thread.sleep(50);
            } catch (InterruptedException ex) {
                Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    private int consume() throws InterruptedException {
        //wait if queue is empty
        while (sharedQueue.isEmpty()) {
            synchronized (sharedQueue) {
                System.out.println("Queue is empty " + Thread.currentThread().getName()
                                    + " is waiting , size: " + sharedQueue.size());

                sharedQueue.wait();
            }
        }

        //Otherwise eat chemical gene as well as notify waiting producer
        synchronized (sharedQueue) {
            sharedQueue.notifyAll();
            return (Integer) sharedQueue.remove(0);
        }
    }
}

Output:
Produced: 0
Queue is empty Consumer is waiting , size: 0
Produced: 1
Consumed: 0
Produced: 2
Produced: 3
Produced: 4
Produced: 5
Queue is total Producer is waiting , size: 4
Consumed: 1
Produced: 6
Queue is total Producer is waiting , size: 4
Consumed: 2
Consumed: 3
Consumed: 4
Consumed: 5
Consumed: 6
Queue is empty Consumer is waiting , size: 0

That’s all on How to solve producer consumer occupation inwards Java using await as well as notify method. I notwithstanding intend that using BlockingQueue to implement producer consumer blueprint pattern is much ameliorate because of its simplicity as well as concise code. At the same fourth dimension this occupation is an fantabulous practise to empathize concept of await as well as notify method inwards Java.

Further Learning
Multithreading as well as Parallel Computing inwards Java
Difference betwixt await as well as slumber method inwards Java

No comments:

Post a Comment