gpt4 book ai didi

java - 内部类内部不能设置静态变量

转载 作者:行者123 更新时间:2023-12-01 09:42:43 25 4
gpt4 key购买 nike

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

下面是我遇到问题的三个文件。更改 Verification 类中的静态变量标志的预期操作应该会终止程序,但事实并非如此。

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;
}

最佳答案

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

您正在从多个不同的线程访问/修改flag,但没有告诉编译器它需要确保正确更新该值以反射(reflect)其他线程上的更改。

来自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 ,问题就会得到解决。

关于java - 内部类内部不能设置静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38336486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com