class Buffer { private String[] queue; private int number; public Buffer (int size) { queue = new String[size]; number = 0; } // Buffer public synchronized void put(String str) { while(number == queue.length) { try { System.out.println("Buffer.put: Väntar..."); wait(); } catch (InterruptedException e) { System.out.println("Buffer.put: Oj!"); } } queue[number++] = str; notify(); } // put public synchronized String get() { while(number == 0) { try { System.out.println("Buffer.get: Väntar..."); wait(); } catch (InterruptedException e) { System.out.println("Buffer.get: Oj!"); } } String s = queue[0]; for (int i = 1; i < number; ++i) queue[i - 1] = queue[i]; --number; notify(); return s; } // get } // class Buffer class WriterThread extends Thread { Buffer b; public WriterThread(Buffer b) { this.b = b; } public void run() { int nrReps = 0; while (true) { String s = "Sträng nummer " + ++nrReps; System.out.println("WriterThread: Lagrar " + s); b.put(s); } } // run } // class WriterThread class ReaderThread extends Thread { Buffer b; public ReaderThread(Buffer b) { this.b = b; } public void run() { while (true) { String s = b.get(); System.out.println("ReaderThread: Hämtade " + s); } } // run } // class ReaderThread public class NotifyExample { public static void main(String[] args) { Buffer b = new Buffer(100); WriterThread w = new WriterThread(b); ReaderThread r = new ReaderThread(b); w.start(); r.start(); } // main } // class NotifyExample