public class Table extends LinkedList { private int capity; public Table(int capity) { super(); this.capity = capity; } public synchronized void addFood(Food food){ while(size() >= capity){ try { wait(); } catch (InterruptedException e) { System.out.print("has error:" + e.getMessage()); e.printStackTrace(); return; } } System.out.println("Add one product now size is:" + size()); this.add(food); notifyAll(); } public synchronized Food getFood(){ while(size() <= 0){ try { wait(); } catch (InterruptedException e) { System.out.print("has error:" + e.getMessage()); e.printStackTrace(); return null; } } System.out.println("Get one product now size is:" + size()); Food food = (Food)this.removeFirst(); notifyAll(); return food; } } 以上是定义一个同步Table public class Worker extends Thread { private Table table; private String name; public void run() { while(true){ Food food = product(); table.addFood(food); System.out.println("Worker[" + name + "] produce one product"); } } private Food product() { Random random = new Random(); try { Thread.sleep(5500+random.nextInt(500)); } catch (InterruptedException e) { System.out.println("Worker[" + name + "] sleep error"); e.printStackTrace(); } return new Food(); } private void addFood(Food food){ table.addFood(food); } public Worker(String name, Table table) { super(); this.name = name; this.table = table; } } 生产者 public class Customer extends Thread{ private String name; private Table table; public Customer(String name,Table table) { super(); this.name = name; this.table = table; } private void eat(Food food){ Random random = new Random(); try { Thread.sleep(4500+random.nextInt(500)); } catch (InterruptedException e) { System.out.print("Customer[" + name + "] sleep error"); e.printStackTrace(); } food = null; } private Food getFood(){ return table.getFood(); } public void run() { while(true){ Food food = getFood(); System.out.println("customer[" + name + "] eat one product"); eat(food); } } } 消费者 public class CustomerTest { /** * @param args */ public static void main(String[] args) { int productSize = 10; int customerSize = 8; int tableSize = 12; Table table = new Table(tableSize); Thread[] workers = new Thread[productSize]; Thread[] customers = new Thread[customerSize]; for(int i = 0; i < productSize;i++){ Worker worker = new Worker("worker" + i,table); workers[i] = worker; } for(int i = 0; i < customerSize;i++){ Customer customer = new Customer("customer" + i,table); customers[i] = customer; } for(int i = 0; i < workers.length; i++){ workers[i].start(); } for(int i = 0; i < customers.length; i++){ customers[i].start(); } } } 测试类