/* * @(#)Lecture9.java 1.0 04/03/31 * * You can modify the template of this file in the * directory ..\JCreator\Templates\Template_1\Project_Name.java * * You can also create your own project template by making a new * folder in the directory ..\JCreator\Template\. Use the other * templates as examples. * */ package myprojects.lecture9; class Lecture9 { static boolean goOn = true; public static void main(String args[]) { Buffer b = new Buffer(); Thread w1 = new Thread( new Writer(b, 0,2) ); Thread w2 = new Thread( new Writer(b, 1,2) ); Thread r = new Thread( new Reader(b) ); w1.start(); w2.start(); r.start(); try{Thread.sleep(2000);}catch(Exception o){}; goOn = false; System.out.println("done"); System.exit(1); } } class Buffer { int buf; boolean empty = true; synchronized void insert(int i){ while (! empty){ try{this.wait();}catch(InterruptedException ie){} }; buf = i; empty = false; this.notifyAll(); } synchronized int get(){ while (empty){ try{this.wait();}catch(InterruptedException ie){} } empty = true; int res = buf; this.notifyAll(); return res; } } class Reader implements Runnable { Buffer b; Reader(Buffer b){ this.b=b; } public void run(){ while(Lecture9.goOn){ System.out.print(b.get() + ", "); } } } class Writer implements Runnable { int counter, step; Buffer b; Writer(Buffer b, int init, int st){ this.b = b; counter = init; step = st; } public void run(){ while(Lecture9.goOn){ b.insert(counter); counter += step; } } }