class MyResorces {
private volatile boolean FLAG = true;
private AtomicInteger atomicInteger = new AtomicInteger();
BlockingQueue<String> blockingDeque = null;
//构造器注入
public MyResorces(BlockingQueue<String> blockingDeque) {
this.blockingDeque = blockingDeque;
System.out.println(blockingDeque.getClass().getName());
}
public void myProvider() throws InterruptedException {
String data = null;
boolean retValue;
while (FLAG) {
data = atomicInteger.incrementAndGet() + "";
retValue = blockingDeque.offer(data, 2L, TimeUnit.SECONDS);
if (retValue) {
System.out.println(Thread.currentThread().getName() + "\t 生产者生产了" + data);
} else {
System.out.println(Thread.currentThread().getName() + "\t 生产者生产失败了");
}
//TimeUnit.SECONDS.sleep(1);
}
System.out.println("关门了");
}
public void myConsumer() throws InterruptedException {
String resutl = null;
while (FLAG) {
resutl = blockingDeque.poll(2L,TimeUnit.SECONDS);
if (resutl == null || resutl.equals("")) {
FLAG = false;
System.out.println(Thread.currentThread().getName() + "\t 超过了俩秒没消费 把标记改为False告诉生产者别生产了");
return;
}
System.out.println(Thread.currentThread().getName() + "\t 消费者消费了" +resutl);
}
}
public void stop() {
FLAG = false;
}
}
public class ProCsu_BlockQueueDemo {
public static void main(String[] args) {
MyResorces myResorces = new MyResorces(new ArrayBlockingQueue<>(10));
new Thread(() -> {
try {
myResorces.myProvider();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "A").start();
new Thread(() -> {
try {
myResorces.myConsumer();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "B").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
myResorces.stop();
}
}
手写一个生产者消费者_阻塞队列。
最新推荐文章于 2025-04-27 21:50:54 发布
本文通过使用阻塞队列实现生产者消费者模式,演示了如何在多线程环境下进行资源的生产和消费。代码中,生产者不断生成数据并尝试将其放入队列,而消费者则从队列中取出数据进行处理,当超过指定时间未消费到数据时,系统将停止生产。

2237

被折叠的 条评论
为什么被折叠?



