简体   繁体   English

在 Java 中切换易失性 boolean

[英]Toggle a volatile boolean in Java

I notice that the following code doesn't toggle the flag as it is intended to be (the flag value remains the same after toggleFlag is called).我注意到以下代码没有按预期切换标志(调用 toggleFlag 后标志值保持不变)。 Why is this the case?为什么会这样?

private static volatile boolean flag;

static synchronized void toggleFlag() {
   flag = !flag;
}

It is impossible for the code you put to compile, leave running.您放置的代码无法编译,继续运行。

Your code has multiple errors, for example,您的代码有多个错误,例如,

  1. You can't access a non-static variable( flag in this case) from a static method( toggle() in this case).您无法从static方法(在本例中为toggle()访问non-static变量(在本例中为flag )。
  2. Proper declaration of toggle() method is, static synchronized void toggle() toggle()方法的正确声明是static synchronized void toggle()

Correct code:正确代码:

private static volatile boolean flag;

static synchronized void toggle()
{
 flag = !flag;
}

Thank you.谢谢你。

You cannot use this with static variable.您不能将this与 static 变量一起使用。

In static block or a static method, there is no instance to refer to, and therefore the this keyword is not permitted.在 static 块或 static 方法中,没有可引用的实例,因此不允许使用this关键字。

Check this out:看一下这个:

private static volatile boolean flag;

    static synchronized void toggleFlag() {
        flag = !flag;
    }

From docs.oracle.com:来自 docs.oracle.com:

Not all combinations of instance and class variables and methods are allowed:并非所有实例和 class 变量和方法的组合都是允许的:

  • Instance methods can access instance variables and instance methods directly.实例方法可以直接访问实例变量和实例方法。
  • Instance methods can access class variables and class methods directly.实例方法可以直接访问 class 变量和 class 方法。
  • Class methods can access class variables and class methods directly. Class 方法可以直接访问 class 变量和 class 方法。
  • Class methods cannot access instance variables or instance methods directly—they must use an object reference. Class 方法不能直接访问实例变量或实例方法——它们必须使用 object 引用。 Also, class methods cannot use the this keyword as there is no instance for this to refer to.此外,class 方法不能使用 this 关键字,因为没有 this 可以引用的实例。

Link: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html链接: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

UPD. UPD。 When you create boolean variable such as private static volatile boolean flag;当您创建boolean变量时,例如private static volatile boolean flag; it becomes false by default.默认情况下它变为false So using this code toggleFlag();所以使用这个代码toggleFlag(); means !false .意味着!false

You can check the Default Values section in Primitive Data Types for more information about the class members default values.您可以查看原始数据类型中的默认值部分,了解有关 class 成员默认值的更多信息。

Link: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html链接: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM