0

I am parsing an XML document, building an object from the information that I parse, and then putting that object into a blocking queue.

For testing purposes, the size of the blocking queue is 3 and I have 4 pages that I need to process. What I'd like to happen is that after all possible objects have been added they should all be taken off. I've tried using a while loop (as shown below) to take all the elements out of the queue but a there seems to be a null preventing it from going through the rest of the queue.

I'm new to threads in Java and I'm guessing that's where my trouble lies.

Any help would be appreciated.

Runnable parser = new Runnable()
{
    public void run()
    {
        try
        {
            saxParser.parse("file_to_parse.xml", handler);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
};

Runnable takeOff = new Runnable()
{
    public void run()
    {
        try
        {
            while(handler.bq.peek() != null)
            {
                handler.bq.take();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
};

new Thread(parser).start();
new Thread(takeOff).start();
4

1 回答 1

3

一个问题是take会阻塞空队列(poll是在空队列上返回 null 的方法),因此您的循环不会终止(除非parser将 null 添加到队列中,这应该是一个错误)。您也take经常调用 - 第一次take调用(在 while 循环的守卫中)正在删除一个元素,然后第二次take调用(在 while 循环内)正在删除另一个元素,这意味着您正在丢弃队列的一半元素。尝试这样的事情

try {
    String temp;
    while((temp = handler.bq.poll()) != null) {
        // process temp
    }
}

仅当您在完成将项目添加到队列时才开始(当takeOff返回false 时),这才会起作用 - 否则可能会返回 null 并在仍在向队列中添加项目时终止。这是一个替代方案,可让您同时运行parserofferpolltakeOffparserparsertakeOff

String temp;
try {
    while(true) {
        temp = handler.bq.take();
        // process temp
    }
catch (InterruptedException ex) {
    // ignore exception
}
while((temp = handler.bq.poll()) != null) {
    // process temp
}

然后你需要线程何时完成:这interrupt()将退出循环,之后线程将进入循环以完成从队列中删除项目。takeOffparserwhile(true)while((temp = handler.bq.poll()) != null)

于 2013-06-24T16:06:39.560 回答