I have a question in java concurrency.
I use the sout in Producer
thread with class variable private static boolean FLAG
and you can already see FLAG
variable without volatile.
I want to change FLAG = true
to FLAG = !FLAG
in Producer
thread and after that I expected to read this value in Consumer
thread.
Ofcourse FLAG
doesn’t have volatile and Consumer
thread will read the old FLAG
value.
So when I change position
System.out.println("Flag to " + !FLAG);
FLAG = !FLAG;
private static boolean FLAG = true;
public static void main(String[] args) {
new Consumer().start();
new Producer().start();
}
static class Consumer extends Thread {
@Override
public void run() {
boolean local = FLAG;
while ( local ){
local = FLAG;
if (!local) {
System.out.println("exit");
}
}
}
}
static class Producer extends Thread{
@Override
public void run() {
System.out.println("Flag to " + !FLAG);
FLAG = !FLAG;
}
}
to
private static boolean FLAG = true;
public static void main(String[] args) {
new Consumer().start();
new Producer().start();
}
static class Consumer extends Thread {
@Override
public void run() {
boolean local = FLAG;
while ( local ){
local = FLAG;
if (!local) {
System.out.println("exit");
}
}
}
}
static class Producer extends Thread{
@Override
public void run() {
FLAG = !FLAG;
System.out.println("Flag to " + !FLAG);
}
}
FLAG = !FLAG;
System.out.println("Flag to " + !FLAG);
Consumer
thread printing the " exit ".
So where is the my fault or what is the explanation this case.