1.特点
优点:解藕,异步,平衡速度差异
生产者线程:“生产”产品,并把产品放到一个队列里;
消费者线程:“消费”产品。
2.生产者
生产”产品,并把产品放到一个队列里;队列也是有最大容量的。
当达到最大容量,生产者必须停下来,调用wait()
1.生产商品
2.队列有对象,通过其他线程消费
3.如果队列满了,暂停wait()
public class Producer implements Runnable{
private Queue<Product> queue;
private int maxCapacity;
public Producer(Queue queue, int maxCapacity) {
this.queue = queue;
this.maxCapacity = maxCapacity;
}
@Override
public void run() {
synchronized (queue) {
while (queue.size() == maxCapacity) { //一定要用 while,而不是 if,下文解释
try {
System.out.println("生产者" + Thread.currentThread().getName() + "等待中... Queue 已达到最大容量,无法生产");
queue.wait();
System.out.println("生产者" + Thread.currentThread().getName() + "退出等待");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (queue.size()> 0) { //队列里的产品从无到有,需要通知在等待的消费者
queue.notifyAll();
}
Random random = new Random();
Integer i = random.nextInt();
queue.offer(new Product("产品" + i.toString()));
System.out.println("生产者" + Thread.currentThread().getName() + "生产了产品:" + i.toString());
}
}
}
2.消费者
1.消费者处理任务
2.当队列里没有任务,阻塞等待
public class Consumer implements Runnable{
private Queue<Product> queue;
private int maxCapacity;
public Consumer(Queue queue, int maxCapacity) {
this.queue = queue;
this.maxCapacity = maxCapacity;
}
@Override
public void run() {
synchronized (queue) {
while (queue.isEmpty()) {
try {
System.out.println("消费者" + Thread.currentThread().getName() + "等待中... Queue 已缺货,无法消费");
queue.wait();
System.out.println("消费者" + Thread.currentThread().getName() + "退出等待");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Product product = queue.poll();
System.out.println("消费者" + Thread.currentThread().getName() + "消费:" + product.getName());
}
}
}
总结:生产者消费者模型是重要的线程类并发知识点。
参考:https://segmentfault.com/a/1190000024444906,对于错误点就行了纠正。