Import Java.util.linkedlist;import java.util.queue;import java.util.random;/** * Simple Java program to demonstrate how T o use Wait, notify and Notifyall () * method in Java by solving producer consumer problem. * * @author Javin Paul */public class Producerconsumerinjava {public static void main (String args[]) {SYSTEM.O Ut.println ("How to use Wait and notify method in Java"); System.out.println ("Solving Producer consumper problem"); queue<integer> buffer = new linkedlist<> (); int maxSize = 10; Thread producer = new producer (buffer, MaxSize, "producer"); Thread consumer = new Consumer (buffer, maxSize, "consumer"); Producer.start (); Consumer.start (); }}/** * Producer Thread would keep producing values for Consumer * to Consumer. It would use the wait () method when the Queue is full * and use Notify () method to send notification to Consumer * Thread. * * @author WINDOWS 8 * */class Producer extends thread{private queue<integer> Queue private int maxSize; Public Producer (queue<integer> queue, int maxSize, String name) {super (name); this.queue = queue; this.maxsiz e = maxSize; } @Override public void Run () {while (true) {synchronized (queue) {while (queue.size () = = maxSize) {try {System.out. println ("Queue is full," + "Producer thread waiting for" + "Consumer to take something from queue"); Queue.wait (); } catch (Exception ex) {ex.printstacktrace ();} } Random random = new random (); int i = Random.nextint (); System.out.println ("Producing value:" + i); Queue.add (i); Queue.notifyall (); }}}}/** * Consumer Thread would Consumer values form Shared Queue. * It'll also use Wait () method to wait if the queue is * empty. It'll also use notify method to send * Notification to producer thread after consuming values * from queue. * * @author WINDOWS 8 * */class Consumer extends Thread {private queue<integer> Queue; private int maxSize; Public Consumer (queue<integer> Queue, int maxSize, String name) {super (name); This.queue = queue; This.maxsize = maxSize; } @Override public void Run () {while (true) {synchronized (queue) {while (queue.ise Mpty ()) {System.out.println ("Queue is empty," + "Consumer thread was waiting" + "for producer thread T O put something in queue "); try {queue.wait (); } catch (Exception ex) {ex.printstacktrace (); }} System.out.println ("Consuming value:" + queue.remove ()); Queue.notifyall (); } } }}
Java simulates producer consumer models with Notifyall and wait ()