I am new to Java8 and multithreading work. I tried this piece of code below
public class Test {
public static boolean bchanged = true;
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
while (true) {
if (bchanged != bchanged) {
System.out.println("here");
}
}
}
}
).start();
new Thread((Runnable) () -> {
while (true) {
bchanged = !bchanged;
}
}).start();
}
}
when I was running this code, there is no print of "here". However, when I change
public static volatile boolean bchanged = true;
then the "here" will be printed out.
My original deduction was that, the lambda will have a local copy of the boolean value, and it won't affect the other thread when it is not volatile, but when I tried print out the boolean value in both threads, it proved I was wrong. So I am very confused in this case, how volatile
affect the way lambda work.