- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 GUI 类,按下按钮后,它会为私有(private)静态类变量分配一个值——我们称之为 strX。
类 GUI 的构造函数还实例化一个子类(在同一包中)。该子类实现Runnable,并启动一个线程。线程中有一个无限循环,它不断查询 strX 的值,直到它不再为 null。查询是通过调用 GUI 类中的 getter 方法来完成的。
我注意到,即使在按下按钮并将 strX 设置为某个非空值之后,子类中的查询也仅产生 null。
我是 Java 新手,我开始怀疑我的理解是否有缺陷。
我已阅读 Java: cannot access static variable from a different class in the same package及其 4 个答案,解决了与变量名称冲突有关的情况。我的情况肯定不是这样的。我想做的就是使用 getter 方法从子类获取类变量。
如果我的问题的任何方面需要澄清,请告诉我。我会发布代码,但它很长,可能会增加困惑。
好的,首先,我要感谢 Darren Gilroy 的详细回答和代码片段。这消除了我心中的一些困惑,但我仍然有问题。因此,为了清晰起见,我决定创建一个简单的精简版本的代码,并开始测试它。这个简单的 GUI 类有两个按钮,一个称为“Only Instantiate”,另一个称为“Only Instantiate”“设置值并实例化”。
当您按下“仅实例化”时,它会创建另一个名为 PeekAtGUI 的类的实例。在 PeekAtGUI 内部,启动了一个线程。线程调用GUI的静态getter方法来获取GUI中静态类变量strX的当前值。
当您按下“设置值并实例化”按钮时,它首先将 strX 的值设置为新值,然后实例化 PeekAtGUI。
请注意,在调试时,我注释掉了其中一个或另一个实例。
底线是这样的——当我尝试先实例化,然后按另一个按钮设置新值时,PeekAtGUI 似乎没有获取更新的值。但是,如果我通过按一下按钮来实例化并设置值,那么这一切似乎都神奇地起作用了。
不确定发生了什么,任何澄清将不胜感激。再次感谢。
这是代码-
package intercom;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GUI {
private JFrame frame;
private static volatile String strX = "";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JButton btnSet = new JButton("Set Value and Instantiate");
btnSet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVal(strX+"+");
new PeekAtGUI(); // When PeekAtGUI instantiated here, it is able to get the new strX
}
});
btnSet.setBounds(106, 94, 224, 23);
panel.add(btnSet);
JButton btnStart = new JButton("Only Instantiate");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//new PeekAtGUI(); // When PeekAtGUI is instantiated here, it is NOT able to get the new strX
}
});
btnStart.setBounds(106, 39, 224, 23);
panel.add(btnStart);
}
public static synchronized void setVal(String str){
strX = str;
GUI.class.notifyAll();
}
public static synchronized String getVal(){
return strX;
}
}
package intercom;
public class PeekAtGUI implements Runnable{
private static String msg = "";
private boolean done = false;
public PeekAtGUI() {
Thread r = new Thread(this, "PeekAtGUI Thread");
r.start();
}
public void run() {
while (done == false){
try {getMsg();}catch (InterruptedException e) {e.printStackTrace();}
System.out.println("Reporting value of strX from PeekAtGUI: " + msg);
}
}
private static synchronized void getMsg() throws InterruptedException{
while((msg==GUI.getVal())){PeekAtGUI.class.wait();}
msg = GUI.getVal();
}
}
最佳答案
在尝试跨线程共享数据之前,您需要花一些时间了解 how Java treats various types of data when it comes to threading :
Even if you access a static value through multiple threads, each thread can have its local cached copy! To avoid this you can declare the variable as static volatile and this will force the thread to read each time the global value.
However, volatile is not a substitute for proper synchronisation! For instance ...
从事情的声音来看,您每次都会读取线程的缓存值 - 您可能会或可能不会看到更改,并且尝试使您的程序可预测地执行将是一个严重头痛。阅读 stivlo's answer 的其余部分,并考虑为线程之间的通信提供更合理的设计。
关于java - 没有看到静态类变量从在单独线程中运行的同一包中的另一个类更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23619936/
如何获取特定 UTF-8 字符串的字节序列?我看到正则表达式引擎中的某些错误仅在某些边缘情况下才会触发,我想确切地知道它正在处理哪些数据。 最佳答案 也许 charToRaw ? > charToRa
考虑一个具有许多变量的 java 程序,其中一些是循环计数器,我希望看到这些变量随时间变化的值,而不是在代码中到处放置 print 语句。 为什么?我认为它可以帮助我轻松调试。 Example- in
有没有办法查看 JavaScript 正在创建的“线程”?例如,如果我有一个附加到 DOM 元素的事件处理程序,我假设 JavaScript 会隐式地创建一个新线程来在后台运行该代码?如果是这样,有没
我正在使用反射 API 来调用类运行时并调用其方法。但我看到 java.lang.reflect.InitationTargetException 异常。 我需要调用一个名为 - TestClass
考虑一个名为 t.cmd 的命令脚本,它只包含以下两行: @exit /b 123 @echo If you see this, THEN EXIT FAILED.. 因此,该脚本只是将脚本执行过程的
我最近一直在努力学习编程语言实用学第 3 版,以了解更多关于语言在底层如何工作的信息,并且通过查看由真正基本的 GCC 编译的 C 代码生成的程序集,我获得了很多进展.我开始对 C 系列的静态语言越来
最简单的制作方法是什么QWebView识别并正确加载网页上的 Flash? 最佳答案 似乎只需两行即可实现(当然,假设目标系统上安装了闪存): QWebSettings *settings = QWe
我想通过编程(使用VBA)访问其他人与我共享的日历。它们在我的Outlook中的“人民日历”下列出。我在网上搜索了此内容,所有建议所做的仅使我感到困惑。如何从“人的日历”中获取共享给我的所有日历的
使用MongoDB Compass,可以看到数据库用户或创建新用户吗? 最佳答案 香港专业教育学院在命令行上使用以下命令进行管理: mongo use (my database name) db.cr
我正在CentOS 7.4.1708(核心),Java(TM)SE运行时环境(内部版本1.8.0_152-b16)上运行eXist-db 3.6.1。我希望能够在person.xml中的最后一个记录之
我需要确认。 客户端 1 在事务内的表中插入行。 客户端 2 使用 SELECT 请求该表。如果在此客户端上隔离级别设置为 READ COMMITTED,您能否确认 SELECT 不会返回客户端 1
我刚刚安装了 python-dev: $ sudo apt-get install python-dev 这样我就可以开始使用 P4Python 了。但是当我尝试导入 P4 时,我得到: Traceb
我正在使用 msys 和 mingw 编译 libtorrent-rasterbar-0.16.16。./configure 运行良好,直到它进入 boost 库检查。我有 boost 1.51,我设
我在 GO 项目的 Travis CI 上有一个奇怪的行为。 [这里] 失败了,提示一个函数只接受 1 个参数并用 2 个参数调用。 src/finances-service/main.go:45:1
这个问题已经有答案了: What are enums and why are they useful? (27 个回答) 已关闭 4 年前。 作为 Java 初学者,我接触到了枚举,这让我对类型声明感
关闭。这个问题是off-topic .它目前不接受答案。 想改进这个问题吗? Update the question所以它是on-topic用于堆栈溢出。 关闭 11 年前。 Improve thi
我正在使用 preactjs 创建我的应用程序。最重要的是,我正在使用剑道网格。在网格内,我想显示一个超链接。如果用户点击链接,它应该改变路线。为了呈现链接,我使用了 preact-router。 这
有没有办法只查看 Node.js 中的函数签名?我知道 fn.toString() 但不需要所有代码,只需要签名。 最佳答案 var source = fn.toString(); var signa
如何设置 vim 以查看我在 ubuntu 上安装的 ruby rvm。 rvm 已安装,ruby 从终端返回。 renshaw@renshaw-TravelMate-5740G:~$ ruby
我试图在我的 Android 应用程序中防止 OutOfMemoryError。我已经阅读了很多帖子,但我仍然无法解决。 该应用程序有后台 Activity ,所以我认为这是主要问题。 OutOfMe
我是一名优秀的程序员,十分优秀!