gpt4 book ai didi

java - 为什么使用ArrayBlockingQueue时程序会挂起

转载 作者:行者123 更新时间:2023-12-01 09:20:14 24 4
gpt4 key购买 nike

我在使用 ArrayBlockingQueue 时遇到问题。

这是我的代码:

package study;

import org.pmw.tinylog.Logger;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class App {
public static void main(String[] args) throws Exception {
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1024);
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);

new Thread(producer).start();
new Thread(consumer).start();

Thread.sleep(1000);
}
}

class Producer implements Runnable {
protected BlockingQueue<String> queue = null;

public Producer(BlockingQueue<String> queue) {
this.queue = queue;
}

@Override
public void run() {
try {
for (int i = 0; i < 100000; i++) {
queue.put(String.valueOf(i));
//Thread.sleep(1000);
}
} catch (InterruptedException e) {
Logger.info(e);
}
}
}

class Consumer implements Runnable {
protected BlockingQueue queue;

public Consumer(BlockingQueue queue) {
this.queue = queue;
}

@Override
public void run() {
try {
Logger.info(queue.take());
//Logger.info(queue.take());
//Logger.info(queue.take());
} catch (InterruptedException e) {
Logger.info(e);
}
}
}

但是输出是:

2016-10-24 14:08:27 [Thread-1] study.Consumer.run()
INFO: 0

我认为这是不正确的,但我找不到问题所在。

最佳答案

将您的Consumer的运行更改为循环,因为此时您只从队列中取出第一个元素,而Producer已放入100000 进入队列。

 public void run() {
while (true) {
try {
Logger.info(queue.take());
//Logger.info(queue.take());
//Logger.info(queue.take());
} catch (InterruptedException e) {
Logger.info(e);
}
}
}

关于java - 为什么使用ArrayBlockingQueue时程序会挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40211720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com