Java 8: how volatile fields work with lambda

I'm new to Java 8 and multithreading I tried this 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 run this code, there is no "here" print But when I change

public static volatile boolean bchanged = true;

Then "here" will be printed

My original inference is that lambda will have a local copy of the Boolean value. When it is not volatile, it will not affect another thread, but when I try to print the Boolean value in two threads, it proves me wrong So I am very confused in this case, how to affect the working mode of lambda

Solution

This is not about Lambdas, but about accessing shared variables in multiple threads You need to use synchronized, locks, atomicboolean, volatile, or some other thread - safe alternative Using the code you write, the compiler may cache the value of bchanged It does not know that another thread has modified it, so the first thread sees an outdated cache value

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>