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

qq_37966597 qq_37966597 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区


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的时间片就到了,跳到取出的操作。如果是这个问题的话,有办法让输出也能够一致么
...全文

相关推荐

评论 1
收藏 已收藏
分享
返回顶部
qq_37966597
Java SE 62,621 成员 307,251 内容