0

根据 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) {行。

4

1 回答 1

0

getTick()线程安全吗?即在到达刻度值的途中是否有同步的关键字、某种形式的锁、易失性读取或原子变量?如果没有,您的线程可能看不到对滴答计数器所做的并发更改。中断和调试可能会迫使这些更改可见。

此外,您的生产者似乎不应该等待成功queue.put(),而是等待应用程序进入下一个刻度。是myWorld.myApp.getTick()阻塞吗?如果没有,您的代码将无限循环,除非:

  • 有其他线程同时修改tick
  • 您的线程被挂起,另一个被唤醒的线程修改了刻度

使用无限循环检查条件的变化(又名轮询/旋转等待)只有在可能发生变化的情况下才有意义。

我建议waitForTick(int tick)在对象中实现阻塞和安全发布myWorld.myApp。除了线程安全集合之外,还有其他并发组件,如信号量、屏障等,可用于同步不同的线程。

于 2013-02-17T05:39:00.877 回答