在学习完 RabbitMQ 后,才明白为什么那么喜欢问生产者-消费者问题,因为在很多开发领域都能派上用场。
在 Java基础 以及 操作系统 都有接触,但还是要在这里再总结一下。
文章目录
实现方式
生产者消费者问题是线程模型中的经典问题:生产者和消费者在同一时间段内共用同一存储空间,生产者向空间里生产数据,而消费者取走数据。
保证同一时刻只有一个线程读或写:
- 用synchronized对存储加锁,然后用object原生的wait() 和 notify()做同步
- 用concurrent.locks.Lock,然后用condition的await() 和signal()做同步
- 使用信号量semaphore
保证存储内部的读写唯一
- 直接使用concurrent.BlockingQueue
- 使用PipedInputStream/PipedOutputStream
synchronized、wait()、notify()
- wait():当缓冲区已满/空时,生产者/消费者线程停止自己的执行,放弃锁,使自己处于等待状态,让其他线程执行。
- notify():当生产者/消费者向缓冲区放入/取出一个产品时,向其他等待的线程发出可执行的通知,同时放弃锁,使自己处于等待状态。
实现
public class Main {
static int i = 0;
static int size = 10;
Queue<String> queue = new LinkedList<String>();
public static void main(String[] args) {
Main main = new Main();
main.new Producter("producter[1]").start();
main.new Producter("producter[2]").start();
main.new Consumer("consumer[1]").start();
main.new Consumer("consumer[2]").start();
main.new Consumer("consumer[3]").start();
}
//生产者
class Producter extends Thread{
private String name;
public Producter(String name) {
this.name = name;
}
@Override
public void run() {
while(true){
synchronized (queue) {
while(queue.size()==size){
System.out.println("The queue is full! "+name+" is waiting for Consumer");
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name+":product====>production_"+i);
queue.offer("production_" + i);
i++;
queue.notifyAll();
}
try {
sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消费者
class Consumer extends Thread{
private String name;
public Consumer(String name) {
this.name = name;
}
@Override
public void run() {
while(true){
synchronized (queue) {
while(queue.isEmpty()){
System.out.println("The queue is empty! "+name+" is waiting for Producter");
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String s = queue.poll();
System.out.println(name+":consume====>"+s);
queue.notifyAll();
}
try {
sleep(new Random().