场景:生产者生产口罩,消费者消费口罩
1、定义一个口罩的实体类
/**
* 定义一个口罩的实体类
*/
public class KouZhao {
private Integer id;
private String type;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
2、生产者代码
import java.util.concurrent.BlockingQueue;
/**
* 生产者代码
* @since 2022/10/25
*/
public class Producer implements Runnable{
private BlockingQueue<KouZhao> queue;
public Producer(BlockingQueue<KouZhao> queue){
this.queue = queue;
}
private int index =0;
@Override
public void run() {
while (true){
try {
Thread.sleep(500);
if(queue.remainingCapacity()<=0){
System.out.println("口罩堆积太多了,快来买吧...");
}
else{
KouZhao kouZhao = new KouZhao();
kouZhao.setId(index++);
kouZhao.setType("N95");
System.out.println("正在生产第"+index+"个口罩");
queue.add(kouZhao);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3、消费者代码
import java.util.concurrent.BlockingQueue;
/**
* 消费者代码
* @since 2022/10/25
*/
public class Consumer implements Runnable{
private BlockingQueue<KouZhao> queue;
public Consumer(BlockingQueue<KouZhao> queue){
this.queue = queue;
}
@Override
public void run() {
while (true){
try {
Thread.sleep(1000);
System.out.println("正在准备购买口罩。。。");
KouZhao kouZhao = queue.take();
System.out.println("正在购买第"+kouZhao.getId()+
" "+kouZhao.getType()+"口罩");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
4、测试代码
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
* 测试代码
* @since 2022/10/25
*/
public class App {
public static void main(String[] args) {
BlockingQueue<KouZhao>queue = new ArrayBlockingQueue<>(10);
new Thread(new Producer(queue)).start();
new Thread(new Consumer(queue)).start();
}
}
5、效果图
1、 生产者生产的速度大于消费的速度时:当消息队列空间满了之后 生产者进入阻塞状态,直到消费者消费成功 消息队列有空余时间后,生产者会继续生产消息
2、当消费者消费速度大于生产者速度时:当消息队列为空时,消费者进入阻塞状态,直到生产者生产消息成功放入到队列,消费者才能继续消费
注: 具体测试效果可以通过调整生产者生产时间及消费者消费时间来查看