mar*_*nus 0 java collections multithreading producer-consumer
我想有一个SynchronousQueue从一个线程插入元素的位置put(),因此输入被阻塞,直到元素被另一个线程占用.
在另一个线程中,我执行了大量计算,并且不时想要检查元素是否已经可用,并使用它.但似乎isEmpty()总是返回true,即使另一个线程正在等待put()通话.
这怎么可能呢?以下是示例代码:
@Test
public void testQueue() throws InterruptedException {
final BlockingQueue<Integer> queue = new SynchronousQueue<Integer>();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (!queue.isEmpty()) {
try {
queue.take();
System.out.println("taken!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// do useful computations here (busy wait)
}
}
});
t.start();
queue.put(1234);
// this point is never reached!
System.out.println("hello");
}
Run Code Online (Sandbox Code Playgroud)
编辑:既不是isEmpty()也不是peek()工作,必须使用poll().谢谢!
来自http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/SynchronousQueue.html#put(E):
isEmpty
public boolean isEmpty()
始终返回true.SynchronousQueue没有内部容量.
(还没有研究这个很详细,但你可能想看看在任调查或采取替代)
| 归档时间: |
|
| 查看次数: |
1499 次 |
| 最近记录: |