内部 class 内无法设置静态变量

Static Variable can not be set inside inner class

所以我遇到了问题,我无法理解为什么在主测试文件中看不到实现 ActionListener 的内部 class 中设置的其他 class 静态变量的原因。

下面是我遇到问题的三个文件 with.The 在验证中更改静态变量标志的预期操作 class 应该终止程序,但它没有。

InnerClassTest File(Main class file)

package innerClass;

public class InnerClassTest
{
   public static void main(String[] args)
   {
        TalkingClock clock = new TalkingClock(2000, true);
        clock.start();
        while(true)
        {
            if(Verification.flag == true)
            {
                System.exit(0);
            }
            if (TalkingClock.flag == true)
            {
                System.exit(0);
            }
        }
   }
}


TalkingClock File

package innerClass;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.Timer;

public class TalkingClock
{
   private int interval;
   private boolean beep;
   public static boolean flag = false;
   public TalkingClock(int interval, boolean beep)
   {
        this.interval = interval;
        this.beep = beep;
   }

   public void start()
   {
        ActionListener listener = new TimePrinter();
        Timer t = new Timer(interval, listener);
        t.start();
   }

   public class TimePrinter implements ActionListener
   {
        @Override
        public void actionPerformed(ActionEvent event)
        {
            Date now = new Date();
            System.out.println("At the tone, the time is " + now);
            if (beep) Toolkit.getDefaultToolkit().beep();
            Verification.flag = true;
            flag = true;
        }
   }
}

Verification Class File

package innerClass;

public class Verification
{
    public static int count = 0;
    public static boolean flag = false;
}

这是因为多线程问题,而不是内部 类 或静态变量。

您 accessing/modifying flag 来自多个不同的线程,但没有告诉编译器它需要确保正确更新该值以反映其他线程上的更改。

来自JLS section 8.3.1.4

The Java programming language allows threads to access shared variables (§17.1). As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.

The Java programming language provides a second mechanism, volatile fields, that is more convenient than locking for some purposes.

A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable

没有该关键字,JVM 和编译器可以自由进行优化,而不允许其他线程进行更改。使 flag volatile 问题将得到解决。