richard
richard

Reputation: 762

How to correctly use variable in java Thread?

I've ran into a strange situation, when I try to use a member variable in the thread I create, it doesn't return the correct value, below is a snippet of my code

new Thread() {
        public void run() {
            while (true) {
                //System.out.println(printQueue.isEmpty());
                while ((currentOrder = printQueue.poll())!= null) {
                    printall();
                }
            }
        }
    }.start();

printQueue is a queue I defined, the result is different when I try to push a value into the queue.
when I uncomment the print line,this currentOrder will return a non-null variable,but if I comment that line, currentOrder will always return null. How does it happen and what am I supposed to do to resolve it?

Upvotes: 0

Views: 54

Answers (1)

DaoWen
DaoWen

Reputation: 33019

The LinkedList class isn't designed for use in multithreaded applications. Individual threads can cache the state of the LinkedList in their local memories, which can cause the state to appear inconsistent.

You should probably use a java.util.concurrent.BlockingQueue instead and see if that solves the problem. This is probably an issue with the threads not seeing updates, but writing to System.out is causing the thread-local memory to be flushed.

If you want to learn a bit more about what's going on here you might want to refer to this question:

What does flushing thread local memory to global memory mean?

Upvotes: 2

Related Questions