ArrayBlockingQueue阻塞队列实现生产者消费者模式

qq_37966597 2019-10-24 02:07:36


public class Demo {
@Test
public void test() throws InterruptedException {
new Thread(new Customer()).start();
new Thread(new Producer()).start();
new Thread(new Customer()).start();
new Thread(new Producer()).start();

while (Thread.activeCount() > 2){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}

class Store{
private volatile static Store instance;
private AtomicInteger index;
private ArrayBlockingQueue<Integer> queue;

private Store(){
index = new AtomicInteger();
queue = new ArrayBlockingQueue<>(3);
}

public static Store getInstance(){
if (instance == null){
synchronized (Store.class){
if (instance == null){
instance = new Store();
}
}
}
return instance;
}



public void put(){
int i = index.incrementAndGet();
try {
queue.put(i);
System.out.println("生产:" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public void take(){
Integer take;
try {
take = queue.take();
System.out.println("\t 消费" + take);
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}

class Customer implements Runnable{

private Store store;
public Customer(){
store = Store.getInstance();
}

@Override
public void run() {
for (int i = 0; i < 10; i++){
store.take();
}
}
}
class Producer implements Runnable{

private Store store;
public Producer(){
store = Store.getInstance();
}

@Override
public void run() {
for (int i = 0; i < 10; i++){
store.put();
}
}
}


用ArrayBlockingQueue实现了生产者消费者模式,但是运行输出的时候会出现问题,输出显示的是没生产就有了消费或者生产数超过了最大数。猜测队列的插入和取出没问题,可能是插入完成后,还没输出,CPU的时间片就到了,跳到取出的操作。如果是这个问题的话,有办法让输出也能够一致么
...全文
169 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_37966597 2019-10-25
  • 打赏
  • 举报
回复
有大佬知道么

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧