By
Macintosh-c
总阅读 次
生产者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| package test;
import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger;
public class Producer implements Runnable{ private final Vector sharedQueue; private final int SIZE; public Producer(Vector sharedQueue,int size){ this.sharedQueue=sharedQueue; this.SIZE=size; } @Override public void run() { for(int i=1;i<=20;i++){ try { produce(i); } catch (InterruptedException ex) { Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex); } } } private void produce(int i) throws InterruptedException{ synchronized (sharedQueue) { while(sharedQueue.size()==SIZE){ System.out.println("Queue is full "+Thread.currentThread().getName() +"is waiting,size:"+sharedQueue.size()); sharedQueue.wait(); } sharedQueue.add(i); System.out.println("生产者生产了第"+i+"个商品"); sharedQueue.notifyAll(); } } }
|
消费者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| package test;
import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger;
public class Consumer implements Runnable{ private final Vector sharedQueue; private final int SIZE; public Consumer(Vector sharedQueue,int size){ this.sharedQueue=sharedQueue; this.SIZE=size; } @Override public void run() { while(true){ try { consume(); } catch (InterruptedException ex) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex); } } } private void consume() throws InterruptedException{ synchronized (sharedQueue) { while(sharedQueue.isEmpty()){ System.out.println("Queue is empty"+Thread.currentThread().getName() +"is waiting,size:"+sharedQueue.size()); sharedQueue.wait(); } int cu=(Integer)sharedQueue.remove(0); System.out.println("消费者消费了第"+cu+"个商品"); sharedQueue.notifyAll(); } } }
|
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| package test;
import java.util.Vector;
public class ProducerConsumerSolution { public static void main(String[] args) { Vector sharedQueue=new Vector(); int size=4; Thread prodThread=new Thread(new Producer(sharedQueue,size),"Producer"); Thread consThread=new Thread(new Consumer(sharedQueue,size),"Consumer"); prodThread.start(); consThread.start(); } }
|
------------------------------------------------------------------------------------------------------------------------------
打赏我的人,运气都不会太差哦~
------------------------------------------------------------------------------------------------------------------------------
打赏我的人,运气都不会太差哦~