经典的消费者和生产者的的实现:
注意事项:
1:在循环里面用wait(),因为当线程获得了锁,但是有可能还没有满足其他条件:
2:公用的缓冲池要用锁机制:
1 package demo; 2 3 import java.util.Vector; 4 5 public class Main { 6 7 public static void main(String[] args) { 8 Vectorpool=new Vector (); 9 Producer producer=new Producer(pool, 4);10 Consumer consumer=new Consumer(pool);11 new Thread(producer).start();12 new Thread(consumer).start();13 }14 15 }16 17 //生产者18 class Producer implements Runnable{19 private Vector pool;20 private Integer size;21 22 public Producer(Vector pool, Integer size) {23 this.pool = pool;24 this.size = size;25 }26 @Override27 public void run() {28 for(int i=0;i<7;i++){29 try {30 System.out.println("produce "+i);31 produce(i);32 } catch (InterruptedException e) {33 // TODO Auto-generated catch block34 e.printStackTrace();35 }36 }37 }38 private void produce(int i) throws InterruptedException{39 while(pool.size()==size){40 synchronized (pool) {41 System.out.println("pool is full Producer is waiting,size is "+pool.size());42 pool.wait();43 }44 }45 synchronized (pool) {46 pool.add(i);47 pool.notifyAll();48 }49 }50 }51 52 53 //消费者54 class Consumer implements Runnable{55 private Vector pool;56 public Consumer(Vector pool) {57 this.pool = pool;58 }59 60 @Override61 public void run() {62 for(int i=0;i<7;i++){63 try {64 System.out.println("consume "+i);65 consume();66 } catch (InterruptedException e) {67 // TODO Auto-generated catch block68 e.printStackTrace();69 }70 }71 }72 73 private void consume() throws InterruptedException{74 while(pool.isEmpty()){75 synchronized (pool) {76 System.out.println("pool is empty Consumer is waiting,size is "+pool.size());77 pool.wait();78 }79 }80 synchronized (pool) {81 pool.notifyAll();82 pool.remove(0);83 84 }85 }86 }
执行结果是: