【发布时间】:2013-02-01 19:22:45
【问题描述】:
我有一组生产者-消费者线程,但根据 JConsole 堆栈跟踪,生产者被困在不是.put() 的代码行上。
class Producer implements Runnable {
private final BlockingQueue<CopyOnWriteArrayList<Creature>> queue;
private World myWorld;
Producer(BlockingQueue<CopyOnWriteArrayList<Creature>> q, World myWorld) {
queue = q;
this.myWorld = myWorld;
}
public void run() {
int nextTick = myWorld.myApp.getTick(); //'tick' is the current frame our main loop is on.
while (true) {
if (myWorld.myApp.getTick() >= nextTick) { //if our world has updated to the next frame…
nextTick = myWorld.myApp.getTick() + 1; //increment the next frame to wait for
try {
for (int i = 0; i < myWorld.getCellController()
.getColumns(); i++) {
for (int j = 0; j < myWorld.getCellController()
.getRows(); j++) {
queue.put(myWorld.getCellController().Cells.get(i)
.get(j));
}
}
} catch (InterruptedException ex) {
System.out.println("INT! ******************************");
} catch (NullPointerException ex) {
System.out.println("NULL! ******************************");
} catch (ClassCastException ex) {
System.out.println("CAST! ******************************");
} catch (IllegalArgumentException ex) {
System.out.println("ARG! ******************************");
}
}
}
}
}
根据堆栈跟踪,它只是停留在while(true) 行上,没有通过循环,即使它应该。
Stack trace:
Name: Producer
State: RUNNABLE
Total blocked: 0 Total waited: 196,958
Stack trace:
concurrency.Producer.run(Setup.java:25)
java.lang.Thread.run(Thread.java:680)
第 25 行是 while(true) { 行。
【问题讨论】:
-
您使用的是哪种阻塞队列实现方式?
-
ArrayBlockingQueue和LinkedBlockingQueue都试过了,都挂了。 -
请将 (JConsole) 堆栈跟踪添加到您的问题中。
-
您确定执行路径到达
put行吗?put行周围有条件语句(if/for) -
是的,我很确定。每当我在该行进行调试和中断,并手动推进它时,条件 (if) 的计算结果为 true(我不需要做任何其他事情),我可以手动降低代码就好了。
标签: java multithreading consumer producer