Java Threads
put while the consumer calls
get. We want every item to be consumed exactly
once.public class CubbyHole { private int contents; private boolean available = false; public synchronized int get() { while (available == false) { try { wait(); } catch (InterruptedException e) { } } available = false; notifyAll(); return contents; } public synchronized void put(int value) { while (available == true) { try { wait(); } catch (InterruptedException e) { } } contents = value; available = true; notifyAll(); } } public class ProducerConsumerTest { public static void main(String[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); Consumer c1 = new Consumer(c, 1); p1.start(); c1.start(); } }
synchronized keyword means that only one
thread can be accessing that function at a time.wait method will block until that object
(CubbyHole) calls notifyAll. Since it
blocks it means that some other thread must make that call.7 of 8