用 wait-notify 解决生产者-消费者问题
//生产者
1 package com.mzj.test; 2 import java.util.Vector; 3 import java.util.logging.Level; 4 import java.util.logging.Logger; 5 6 public class Producer implements Runnable { 7 8 private final Vector sharedQueue; 9 private final int SIZE; 10 11 public Producer(Vector sharedQueue, int size) { 12 this.sharedQueue = sharedQueue; 13 this.SIZE = size; 14 } 15 16 @Override 17 public void run() { 18 // TODO Auto-generated method stub 19 for (int i = 0; i < 7; i++) { 20 System.out.println("Produced:" + i); 21 try { 22 produce(i); 23 } catch (InterruptedException ex) { 24 Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex); 25 } 26 } 27 } 28 29 private void produce(int i) throws InterruptedException { 30 31 //wait if queue is full 32 while (sharedQueue.size() == SIZE) { 33 synchronized (sharedQueue) { 34 System.out.println("Queue is full " + Thread.currentThread().getName() 35 + " is waiting , size: " + sharedQueue.size()); 36 sharedQueue.wait(); 37 } 38 } 39 40 //producing element and notify consumers 41 synchronized (sharedQueue) { 42 sharedQueue.add(i); 43 sharedQueue.notifyAll(); 44 } 45 } 46 }
消费者
1 package com.mzj.test; 2 import java.util.Vector; 3 import java.util.logging.Level; 4 import java.util.logging.Logger; 5 6 public class Consumer implements Runnable { 7 8 private final Vector sharedQueue; 9 private final int SIZE; 10 11 public Consumer(Vector sharedQueue, int size) { 12 this.sharedQueue = sharedQueue; 13 this.SIZE = size; 14 } 15 16 @Override 17 public void run() { 18 // TODO Auto-generated method stub 19 while (true) { 20 try { 21 System.out.println("Consumer: " + consume()); 22 Thread.sleep(50); 23 } catch (InterruptedException ex) { 24 Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex); 25 } 26 } 27 } 28 29 private int consume() throws InterruptedException { 30 31 //wait if queue is empty 32 while (sharedQueue.isEmpty()) { 33 synchronized (sharedQueue) { 34 System.out.println("Queue is empty " + Thread.currentThread().getName() 35 + " is waiting , size: " + sharedQueue.size()); 36 sharedQueue.wait(); 37 } 38 } 39 40 //otherwise consume element and notify waiting producer 41 synchronized (sharedQueue) { 42 sharedQueue.notifyAll(); 43 return (Integer) sharedQueue.remove(0); 44 } 45 } 46 }
测试
1 package com.mzj.test; 2 import java.util.Vector; 3 4 public class ProducerConsumerSolution { 5 6 public static void main(String[] args) { 7 Vector sharedQueue = new Vector(); 8 int size = 4; 9 Thread prodThread = new Thread(new Producer(sharedQueue, size), "Producer"); 10 Thread consThread = new Thread(new Consumer(sharedQueue, size), "Consumer"); 11 prodThread.start(); 12 consThread.start(); 13 } 14 }