生产者 Producer.java
import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable {
private BlockingQueue queue;
public Producer(BlockingQueue queue) {
this.queue = queue;
}
private Integer index = 0;
@Override
public void run() {
while (true) {
try {
Thread.sleep(200);
if (queue.remainingCapacity() <= 0) {
System.out.println("口罩已经堆积如山了,大家快来买...");
} else {
KouZhao kouZhao = new KouZhao();
kouZhao.setId(index++);
kouZhao.setType("N95");
System.out.println("正在生产第" + (index - 1) + "号口罩...");
queue.put(kouZhao);
System.out.println("已经生产了口罩:" + queue.size() + "个");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
消费者 Consumer.java
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable {
private BlockingQueue queue;
public Consumer(BlockingQueue queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
System.out.println("正在准备买口罩...");
final KouZhao kouZhao = queue.take();
System.out.println("买到了口罩:" + kouZhao.getId()
+ " " + kouZhao.getType() + "口罩");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
生产消费的实体类 KouZhao.java
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;
}
@Override
public String toString() {
return "KouZhao{" +
"id=" + id +
", type='" + type + ''' +
'}';
}
}
主启动类 App.java
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class App {
public static void main(String[] args) {
BlockingQueue queue =
new ArrayBlockingQueue<>(20);
new Thread(new Producer(queue)).start();
new Thread(new Consumer(queue)).start();
}
}
实现效果



