// PK.java class Producer extends Thread { private Buffer _buf; public Producer(Buffer b) { _buf = b; } public void run() { for (int i = 0; i < 100; ++i) { try { Thread.sleep((int)(50*Math.random())); } catch(Exception e) {} _buf.put(i); } } } class Consumer extends Thread { private Buffer _buf; public Consumer(Buffer b) { _buf = b; } public void run() { for (int i = 0; i < 100; ++i) { try { Thread.sleep((int)(10*Math.random())); } catch(Exception e) {} _buf.get(); } } } class Buffer { private int _buf[]; private int _inbuf = 0; // ile elementow aktualnie w buforze private int _size; // rozmiar bufora public Buffer(int size) { _buf = new int[size]; _size = size; } public boolean isFull() { return (_inbuf == _size); } public boolean isEmpty() { return (_inbuf == 0); } public synchronized void put(int i) { while(isFull()) { // 'condition wait' try { wait(); } catch (InterruptedException e) { } } _buf[_inbuf++] = i; System.out.println("P --> " + i); if (_inbuf == 1) { // produkcja do pustego bufora notify(); } } public synchronized int get() { while(isEmpty()) { // 'condition wait' try { wait(); } catch (InterruptedException e) { } } int i = _buf[0]; // 'dosuniecie' bufora do lewej for (int j = 0; j < _inbuf-1; ++j) { _buf[j] = _buf[j + 1]; } --_inbuf; System.out.println("\tK --> " + i); if (_inbuf == _size-1) { // konsumpcja z pelnego bufora notify(); } return i; } } public class PK { public static void main(String[] args) { Buffer b = new Buffer(10); Producer p = new Producer(b); Consumer c = new Consumer(b); p.start(); c.start(); } }