import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class Queue { private static int MAX_SIZE = 3; private List _list = new ArrayList(); final Lock _lock = new ReentrantLock(); final Condition _notFull = _lock.newCondition(); final Condition _notEmpty = _lock.newCondition(); public void put(String str) { _lock.lock(); while (_list.size() == MAX_SIZE) { System.out.println("Putter, you have to wait until the queue is not full"); try { _notFull.await(); } catch (InterruptedException e) { // ... } } System.out.println("Putter, ok, you can put an item"); _list.add(str); System.out.println("In queue " + _list.size() + " items"); _notEmpty.signal(); _lock.unlock(); } public String get() { _lock.lock(); while (_list.size() == 0) { System.out.println(" Getter, you have to wait until the queue is not empty"); try { _notEmpty.await(); } catch (InterruptedException e) { // } } System.out.println(" Getter, ok, you can get an item"); String str = _list.remove(0); System.out.println("In queue " + _list.size() + " items"); _notFull.signal(); _lock.unlock(); return str; } } class Putter extends Thread { private Queue _queue; public Putter(Queue queue) { _queue = queue; } @Override public void run() { for (int i = 0; i < 100; i++) { _queue.put("item number " + i); } } } class Getter extends Thread { private Queue _queue; public Getter(Queue queue) { _queue = queue; } @Override public void run() { for (int i = 0; i < 100; i++) { _queue.get(); } } } public class ConditionExampleMain { public static void main(String[] args) { Queue queue = new Queue(); Putter putter = new Putter(queue); Getter getter = new Getter(queue); putter.start(); getter.start(); try { putter.join(); getter.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }