import java.util.concurrent.*;import java.util.*;public classConsumerProducer
{public static voidmain(String[] args)
{
ExecutorService executor=Executors.newCachedThreadPool();
executor.execute(newConsumer());
executor.execute(newProducer());
executor.shutdown();
}private static Semaphore mutex = new Semaphore(1);private static Semaphore full = new Semaphore(0);private static Semaphore empty = new Semaphore(20);private static LinkedList q = new LinkedList();private static class Consumer implementsRunnable
{public voidrun()
{try{while ( true)
{
full.acquire();
mutex.acquire();
System.out.println("consume " +q.remove() );
mutex.release();
empty.release();
Thread.sleep((int)(Math.random() * 1000));
}
}catch( InterruptedException ex )
{
ex.printStackTrace();
}
}
}private static class Producer implementsRunnable
{public voidrun()
{try{while ( true)
{
empty.acquire();
mutex.acquire();int data = (int)(Math.random() * 1000);
q.offer(data);
System.out.println("\t\t\t\tproduce " +data);
mutex.release();
full.release();
Thread.sleep((int)(Math.random() * 1000));
}
}catch( InterruptedException ex )
{
ex.printStackTrace();
}
}
}
}