Java实现生产者与消费者模式

时间:2023-03-09 03:05:07
Java实现生产者与消费者模式

  生产者不断向队列中添加数据,消费者不断从队列中获取数据。如果队列满了,则生产者不能添加数据;如果队列为空,则消费者不能获取数据。借助实现了BlockingQueue接口的LinkedBlockingQueue来模拟同步。

 import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; /**
* 生产者消费者模式:使用{@link java.util.concurrent.BlockingQueue}实现
*/
public class Main{
private static final int CAPACITY = 5; public static void main(String args[]){
BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(CAPACITY); Thread producer1 = new Producer("P-1", blockingQueue, CAPACITY);
Thread producer2 = new Producer("P-2", blockingQueue, CAPACITY);
Thread consumer1 = new Consumer("C1", blockingQueue, CAPACITY);
Thread consumer2 = new Consumer("C2", blockingQueue, CAPACITY);
Thread consumer3 = new Consumer("C3", blockingQueue, CAPACITY); producer1.start();
producer2.start();
consumer1.start();
consumer2.start();
consumer3.start();
} /**
* 生产者
*/
public static class Producer extends Thread{
private BlockingQueue<Integer> blockingQueue;
String name;
int maxSize;
int i = 0; public Producer(String name, BlockingQueue<Integer> queue, int maxSize){
super(name);
this.name = name;
this.blockingQueue = queue;
this.maxSize = maxSize;
} @Override
public void run(){
while(true){
try {
blockingQueue.put(i);
System.out.println("[" + name + "] Producing value : " + i);
i++; //暂停最多1秒
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
} /**
* 消费者
*/
public static class Consumer extends Thread{
private BlockingQueue<Integer> blockingQueue;
String name;
int maxSize; public Consumer(String name, BlockingQueue<Integer> queue, int maxSize){
super(name);
this.name = name;
this.blockingQueue = queue;
this.maxSize = maxSize;
} @Override
public void run(){
while(true){
try {
int x = blockingQueue.take();
System.out.println("[" + name + "] Consuming : " + x); //暂停最多1秒
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

  输出结果:

   Java实现生产者与消费者模式

  参考资料

  【Java】生产者消费者模式的实现