/* Producers-Consumers */ /* Multithreads implementation */ /* File Producers_Consumers.java */ /* Main program */ public class Producers_Consumers { public static void main(String[] args) { Buffer b = new Buffer(); new Producer(b,1).start(); new Producer(b,2).start(); new Producer(b,3).start(); new Consumer(b,1).start(); new Consumer(b,2).start(); } } class Producer extends Thread { private Buffer buff; private int id; public Producer(Buffer b, int n) { buff = b; id = n; } public void run() { try { while (!isInterrupted()) { sleep((long)(java.lang.Math.random()*1000)); buff.put(id); } } catch (InterruptedException e) { return; } } } class Consumer extends Thread { private Buffer buff; private int id; public Consumer(Buffer b, int n) { buff = b; id = n; } public void run() { try { while (!isInterrupted()) { sleep((long)(java.lang.Math.random()*1000)); int k = buff.get(); System.out.println("consumer " + id + " has retrieved the datum put by producer " + k); } } catch (InterruptedException e) { return; } } } class Buffer { private int content; private boolean is_empty; public Buffer() { is_empty = true; } public synchronized void put(int k) throws InterruptedException { while (!is_empty) wait(); content = k; is_empty = false; notifyAll(); } public synchronized int get() throws InterruptedException { while (is_empty) wait(); is_empty = true; notifyAll(); return content; } }