生产者和消费者问题是操作系统里面的一个经典问题,用java线程可以来模拟实现。知识点参考: http://blog.youkuaiyun.com/lazy_p/archive/2010/06/02/5642657.aspx 代码如下: package test1; public class ConsumerAndProducer { private int[] buffer = new int[10]; private int index = -1; private String SIGNAL1 = "SIGNAL";//互斥信号量 private String SIGNAL2 = "SIGNAL";//互斥信号量 public static void main(String[] args) { ConsumerAndProducer cp = new ConsumerAndProducer(); cp.new Producer().start(); cp.new Consumer().start(); } private class Producer extends Thread { private void product() { buffer[++index] = index; System.out.println("生产:" + index); } @Override public void run() { while (true) { synchronized (SIGNAL2) { if (index < 9) product(); else { System.out.println("wait Producer"); try { // sleep(1000); SIGNAL1.notify(); SIGNAL2.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } private class Consumer extends Thread { private void consume() { --index; System.out.println("消费" + buffer[index + 1]); } @Override public void run() { while (true) { synchronized (SIGNAL1) { if (index >= 0) { consume(); } else { System.out.println("wait consumer"); try { // sleep(1000); SIGNAL2.notify(); SIGNAL1.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } }