我试图在 BlockingQueue 上使用迭代器方法,发现 hasNext() 是非阻塞的 - 即它不会等到添加更多元素,而是在没有元素时返回 false。
所以这里有问题:
- 这是糟糕的设计,还是错误的期望?
- 有没有办法将 BLockingQueue 的阻塞方法与它的父 Collection 类方法一起使用(例如,如果某个方法期望一个集合,我可以传递一个阻塞队列并希望它的处理将等到队列有更多元素)
这是一个示例代码块
public class SomeContainer{
public static void main(String[] args){
BlockingQueue bq = new LinkedBlockingQueue();
SomeContainer h = new SomeContainer();
Producer p = new Producer(bq);
Consumer c = new Consumer(bq);
p.produce();
c.consume();
}
static class Producer{
BlockingQueue q;
public Producer(BlockingQueue q) {
this.q = q;
}
void produce(){
new Thread(){
public void run() {
for(int i=0; i<10; i++){
for(int j=0;j<10; j++){
q.add(i+" - "+j);
}
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}.start();
}
}
static class Consumer{
BlockingQueue q;
public Consumer(BlockingQueue q) {
this.q = q;
}
void consume() {
new Thread() {
public void run() {
Iterator itr = q.iterator();
while (itr.hasNext())
System.out.println(itr.next());
}
}.start();
}
}
}
此代码最多只打印一次迭代。