Java实现的生产者--消费者程序,还是蛮多问题在里面的,先发上来吧,待我我线程再学一下 package com.thread; public class ProduceAndConsumer { /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { Thread[] prod = new Produce[10]; Thread[] cons = new Consume[9]; for (int i = 0; i < prod.length; ++i) { prod[i] = new Produce(); prod[i].start(); } for (int i = 0; i < cons.length; ++i) { cons[i] = new Consume(); cons[i].start(); } } } class Shop { private static int max = 5; private static volatile int leftProducts = 0; public synchronized void produce() throws InterruptedException { while (leftProducts >= max) { wait(); } notifyAll(); leftProducts++; System.out.println("number of products avaliable: " + leftProducts); } public synchronized void consume() throws InterruptedException { while (leftProducts == 0) { wait(); } notifyAll(); leftProducts--; System.out.println("number of products avaliable: " + leftProducts); } } class Produce extends Thread { Shop s = new Shop(); public synchronized void run() { System.out.print(this.getName()); System.out.println(" is producing......"); try { s.produce(); } catch (InterruptedException e) { e.printStackTrace(); } } } class Consume extends Thread { Shop s = new Shop(); public synchronized void run() { System.out.print(this.getName()); System.out.println(" is consuming......"); try { s.consume(); } catch (InterruptedException e) { e.printStackTrace(); } } }