简体   繁体   中英

Getting value of a thread variable from outside

Lets say i have a thread running like this:

private boolean working = true;

@Override public void run() {
   working = true;
   // do something
   working = false;
   ....
}

and in my main Thread i'm constantly putting out the state of working with

while(threadClassObject.isWorking()) {
    System.out.println(threadClassObject.isWorking());
}

would this work? I tried this example and it seems to work. But is there a way that this could crash? What eg happens if the thread is in the process of changing working while at the exact same time the mainThread tries to read it?

The ans to your question is that it might be working but the above code is a risky code and can break any day. Try making working volatile like

private volatile boolean working = true;

What eg happens if the thread is in the process of changing working while at the exact same time the mainThread tries to read it?

Assignment operation is an atomic operation. So if you have single cpu, two threads can never collide while accessing the variable. If you have more than one cpu, two threads can collide while accessing the variable. For both cases, volatile will make sure that the value is visible to other threads.

NOTE: volatile is good in your situation but if you have more complex data to share across thread try looking into this

Edit:

Adding the comment also part of the soln. to make it more clear.

Basically bcoz of optimization at cpu level, values changed my one thread might not be visible to another. A good example is cpu cache bcoz optimization the values are never reflected in ram where the other thread might be reading. Volatile tells that this variable's value can be changed outside the scope of current thread so no such optimization is done...

You might also want look into doing something with your "runaway" while loop in your main thread:

The current implementation will keep spinning, not leaving much CPU time left for your threads executing run() (or anyone else in the system, for that matter).

You'll need to either use synchronization or AtomicBoolean in order for that to be thread safe. What you have in your code will seem to work, but it's possible that when you check the boolean, it won't be the correct value, so you'll see unexpected results.

No, it is not necessary to lock primitive types like a boolean. If 'working' was an object, then you'd need to use synchronized blocks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM