/* Other examples of threads and synchronization: The basic bounded buffer (producer-consumer) problem: */ class boundedbuffer { private int[] buffer; // circular queue private int front, end, size, max; public boundedbuffer(int m) { max = m; size = front = end = 0; buffer = new int[m]; } public synchronized int read() throws Exception { while (size<1) wait(); // wait 'til there's stuff to read // why "while" and not just "if"? // at this point, thread has been "notified", or woken up int answer = buffer[front]; front = (front + 1) % max; size--; if (size==max-1) notifyAll(); // there's now space for new write return answer; // do we need to wake anyone up at this point? } public synchronized void write(int x) throws Exception { while (size==max) wait(); buffer[end] = x; end = (end+1) % max; size++; if (size==1) notifyAll(); // there's now something to read } } // boundedbuffer /* note that if "notify" is called, only one thread is awoke - it can be a reader or a writer thread. */ class reader implements Runnable { boundedbuffer bb; reader(boundedbuffer x) { bb = x; } public void run() { try { for (int i=0;i<1000;i++) { System.out.println("reader has read "+bb.read()); } } catch (Exception e) {System.out.println(e); System.exit(1);} } // run } class writer implements Runnable { boundedbuffer bb; writer(boundedbuffer x) { bb = x; } public void run() { try { for (int i=0;i<1000;i++) { bb.write(i); System.out.println("writer has written "+i); } } catch (Exception e) {System.out.println(e); System.exit(1);} } // run } public class notes213 { public static void main(String[] args) { try { boundedbuffer bb = new boundedbuffer(20); Thread freddy = new Thread(new reader(bb)); Thread jason = new Thread(new writer(bb)); freddy.start(); jason.start(); freddy.join(); jason.join(); } catch (Exception e) {System.exit(1);} System.exit(0); } }