The answer to your question is that it can work, but the code above is a risky code and can be interrupted any day. Try to make 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?
An assignment operation is an atomic operation. Therefore, if you have one processor, two threads can never collide when accessing a variable. If you have more than one processor, two threads may collide when accessing the variable. In both cases, volatile
will make sure that this value is visible to other threads.
NOTE: volatile
is good in your situation, but if you have more complex data for stream exchange, try exploring this.
Edit:
Adding a comment is also part of Soln. to make it more understandable.
Basically bcoz optimization at the processor level, the values ββchanged my one thread, may not have been visible to another. A good example is ccu cache bcoz optimization, values ββare never reflected in bars where another stream can be read. Volatile reports that this variable value can be changed outside the current thread area, so this optimization is not performed ...
source share