class SoupTest { public static void main(String args[]) { Soup s = new Soup(); Prod p1 = new Prod("p1",s); Prod p2 = new Prod("p2",s); Cons c1 = new Cons("c1",s); Cons c2 = new Cons("c2",s); Cons c3 = new Cons("c3",s); p1.start(); p2.start(); c1.start(); c2.start(); c3.start(); } } /*******************************************************/ class Prod extends Thread { private Soup soup; private String name; private String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public Prod(String n, Soup s) { name = n; soup = s; } public void run() { char c; for (int i = 0; i < 15; i++) { c = alphabet.charAt((int)(Math.random() * 26)); soup.add(c); System.out.println(name+" - Added "+c); try { sleep(0,(int)(Math.random() * 1)); } catch (InterruptedException e) { } } } } /*******************************************************/ class Cons extends Thread { private String name; private Soup soup; public Cons(String n, Soup s) { name = n; soup = s; } public void run() { char c; for (int i = 0; i < 10; i++) { c = soup.eat(); System.out.println(name+" - Eaten "+c); try { sleep((int)Math.random()*2000); } catch(InterruptedException e){} } } } /*******************************************************/ class Soup { private char buffer[] = new char[6]; private int eatnext = 0; private int addnext = 0; private boolean isFull = false; private boolean isEmpty = true; public synchronized char eat() { char toReturn; while (isEmpty == true) { try { wait(); } catch (InterruptedException e) {} } toReturn = buffer[eatnext]; eatnext = (eatnext + 1) % 6; if (eatnext == addnext ) isEmpty = true; isFull=false; notifyAll(); return(toReturn); } public synchronized void add(char c) { while (isFull == true) { try { wait(); } catch (InterruptedException e) {} } buffer[addnext] = c; addnext = (addnext + 1) % 6; if (addnext == eatnext) isFull = true; isEmpty = false; notifyAll(); } }