开发者

Queue not working with thread?

开发者 https://www.devze.com 2023-01-16 08:51 出处:网络
I have the following code that retrieves the first element off a queue only if it has at least 2 elements.For some reason, it\'s not polling the first element.However, if I add a print statement in th

I have the following code that retrieves the first element off a queue only if it has at least 2 elements. For some reason, it's not polling the first element. However, if I add a print statement in there, it will print and poll. The method is in a thread, and there's another thread adding element to the queue, this thread reads from the queue.

...
public void run(){
 开发者_StackOverflow社区   while(beginning){
        int size = queue.size();
        // adding this will cause the program to enter if below: System.out.println(size);
        if(size > 1){
            System.out.println("data: " + queue.poll());
            beginning = false;
        }
    }
}
...

If the println statement is added, it will print

1

1

....

2

data: data

If the println statement is remove, it will not print anything.

Actually, as long as I put something in there, a thread.sleep(1) or a random print statement, it will poll out the data and print it

Thanx for any input.


You need to synchronize on the queue object:

public void run(){ 
    while(beginning){ 
        synchronized (queue) {
            int size = queue.size(); 
            // adding this will cause the program to enter if below: System.out.println(size); 
            if(size > 1){ 
                System.out.println("data: " + queue.poll()); 
                beginning = false; 
            } 
        } 
    }
} 

This will prevent your multiple threads from accessing the queue at the improper times.

You will also have to synchronize the thread that is adding items to the queue in a similar way.


It looks like a synchronization issue.


You should be careful about using a shared resource between threads. You should consider to use a lock ( token ) , acquire it before accessing the queue and releasing it after use.


... turned out that I have to synchronized on the thread to make it work because the queue is implemented by a linkedlist.

But why would a print statement make it work?

0

精彩评论

暂无评论...
验证码 换一张
取 消