An error occurred when calling a local variable in a lambda expression

        

public class Demo1 {
    private static boolean isQuit=false;
    public static void main(String[] args) {
        //boolean isQuit=false;
        Thread thread=new Thread(()->{
            while (!isQuit){
                System.out.println("hello thread");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        thread.start();

        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("标注位修改,进程退出");
        isQuit=true;

    }
}

        The above is a demonstration code for terminating multi-threading by setting the flag bit by the programmer

        isQuit as a member attribute of the class is completely different from the member variable of the main method. When isQuit is used as a member variable of the main method, a compilation error will occur. Why?

the reason for the error

        Lambda expressions have a mechanism such as "variable capture". Lambda expressions do not directly access external variables, but copy external variables into lambdas. However, variable capture has a limitation. The captured variables must It is a constant, or a variable modified by final, so the value of the variable cannot be modified, so it cannot be a flag

Why set variable capture?

     Because the execution timing of the lambda expression is very late, when the lambda expression is actually executed, the local variable isQuit may have been destroyed, and it is unrealistic to access a destroyed local variable in the lambda expression , so lambda introduces the mechanism of variable capture, copying the external variables that need to be called into lambda, and the calling is actually the variable copied by lambda

Why put restrictions on variable capture

        Because java implements "variable capture" by copying, if the external code wants to modify this variable, the external variable will change, and the variable in the lambda expression will not change, so the code is prone to ambiguity, so It is the most worry-free to just let the external variables cannot be changed.

 
 
 
 
   
 

Guess you like

Origin blog.csdn.net/q322359/article/details/131913009
Recommended