在使用BlockingQueue时,我将以下逻辑实现为从它读取的,直到告诉其他。不幸的是,正在断断续续地发生以下情况:
问题是:
。
作为QThread类的一部分,我声明:
public static volatile boolean shouldContinueReading = true;Run (确认正在执行)方法包含:
while (shouldContinueReading) {
try {
String retrieved = qIn.poll(2, TimeUnit.MILLISECONDS);
if (retrieved != null)
consume(retrieved);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("I am out"); // <-- not always seen
if (qIn.remainingCapacity() > 0) {
try {
consume(qIn.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}在此过程中,在另一个线程中,当某些事情发生时,shouldContinueReading会更改状态。
while (stillReading) {
// do nothing
}
QThread.shouldContinueReading = false;更新:问题解决
事实证明,问题还存在得更远:
private void consume(String take) {
// some processing
produce(newData.toString());
}
private void produce(String newData) {
System.out.println(newData);
try {
qOut.put(newData); // <-- Problem is here. Should use offer instead of put
} catch (InterruptedException e) {
e.printStackTrace();
}
}qIn (queue in)和qOut (queue )都声明为:
private volatile BlockingQueue<String> qIn;
private volatile BlockingQueue<String> qOut;对象本身是在其他地方创建的,如下所示并传递给构造函数:
BlockingQueue<String> q1 = new SynchronousQueue<String>();
BlockingQueue<String> q2 = new SynchronousQueue<String>();
QThread qThread = new QThread(q1, q2);有什么建议吗?我该怎么处理qOut?我说的不对吗?
发布于 2012-02-05 02:34:57
我敢打赌,QThread.shouldContinueReading = false;并不总是被执行,或者读取线程一开始就没有执行。也就是说,你所看到的问题很可能发生在河流上游的某个地方--而不是这里。我要做的第一件事就是用100%的自信(多放一些打印语句),找出问题的确切所在。
除了这个问题,我建议使用线程中断机制,而不是滚动自己的标志(这反过来只是一个光荣的标志,但是这样可以影响第三方代码,甚至使实现更简单、更有效),特别是如果这是生产代码。
https://stackoverflow.com/questions/9146131
复制相似问题